[英]plotting 2 graph in same window using matplotlib in python
我在matplotlib
中绘制了折线图和条形图,并且两个脚本都可以正常工作。
但我面临一个问题:
1.如果我想在同一输出窗口中绘制两个图
2.如果我想自定义显示窗口为1024 * 700
在第一种情况下,我使用子图在同一窗口中绘制两个图形,但是我无法为两个图形分别提供各自的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的想法。
当你说
我正在使用子图在同一窗口中绘制两个图形,但是我无法为两个图形分别提供各自的x轴和y轴名称以及各自的标题。
您是否要设置轴标签? 如果是这样,请尝试使用lineGraph.set_xlabel
和lineGraph.set_ylabel
。 另外,在创建绘图之后和创建任何其他绘图之前,请调用plt.xlabel
和plot.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_title
或barChart.set_title
。
fig.add_subplot
返回matplotlib Axes对象。 如Chris所述,该对象上的方法包括set_xlabel
和set_ylabel
。 您可以在http://matplotlib.sourceforge.net/api/axes_api.html上查看Axes对象上可用的全套方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.