在同一个窗口中使用 Python 中的 matplotlib 绘制 2 个图



我正在用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_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

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

最新更新