【问题标题】:plotting 2 graph in same window using matplotlib in python在 python 中使用 matplotlib 在同一窗口中绘制 2 个图形
【发布时间】:2012-05-17 06:30:49
【问题描述】:

我在matplotlib 中绘制了一个折线图和一个条形图,并且两者都可以单独使用我的脚本。
但我面临一个问题:
1. 如果我想在同一个输出窗口中绘制两个图
2.如果我想自定义显示窗口为1024*700

在第一种情况下,我使用 subplot 在同一个窗口中绘制两个图,但我无法为这两个图提供它们各自的 x 轴和 y 轴名称以及它们各自的标题。 我失败的代码是:

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
xs,ys = np.loadtxt("c:/users/name/desktop/new folder/x/counter.cnt",delimiter = ',').T
fig = plt.figure()
lineGraph = fig.add_subplot(211)
barChart = fig.add_subplot(212)

plt.title('DISTRIBUTION of NUMBER')
lineGraph = lineGraph.plot(xs,ys,'-')  #generate line graph
barChart = barChart.bar(xs,ys,width=1.0,facecolor='g') #generate bar plot

plt.grid(True)
plt.axis([0,350,0,25])  #controlls axis for charts x first and then y axis.


plt.savefig('new.png',dpi=400)
plt.show()

但是我无法正确标记这两个图表。
还请提供一些关于如何将窗口大小调整为 1024*700 的想法。

【问题讨论】:

标签: python graph matplotlib


【解决方案1】:

当你说

我正在使用 subplot 在同一个窗口中绘制两个图表,但我无法为这两个图表提供它们各自的 x 轴和 y 轴名称以及它们各自的标题。

您的意思是要设置轴标签吗?如果是这样,请尝试使用lineGraph.set_xlabellineGraph.set_ylabel。或者,在创建绘图之后和创建任何其他绘图之前调用 plt.xlabelplot.ylabel。例如

# Line graph subplot
lineGraph = lineGraph.plot(xs,ys,'-')
lineGraph.set_xlabel('x')
lineGraph.set_ylabel('y')

# Bar graph subplot
barChart = barChart.bar(xs,ys,width=1.0,facecolor='g')
barChart.set_xlabel('x')
barChart.set_ylabel('y')

这同样适用于标题。调用plt.title 将为当前活动的情节添加一个标题。这是您创建的最后一个图或您使用plt.gca 激活的最后一个图。如果您想要特定子图上的标题,请使用子图句柄:lineGraph.set_titlebarChart.set_title

【讨论】:

    【解决方案2】:

    fig.add_subplot 返回一个 matplotlib Axes 对象。如 Chris 所述,该对象上的方法包括 set_xlabelset_ylabel。您可以在 http://matplotlib.sourceforge.net/api/axes_api.html 上查看 Axes 对象上可用的完整方法集。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      相关资源
      最近更新 更多