【发布时间】:2017-05-05 21:35:30
【问题描述】:
我绘制了一个类似于以下内容的图:
它是使用以下代码创建的:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
# 1. Plot a figure consisting of 3 separate axes
# ==============================================
plotNames = ['Plot1','Plot2','Plot3']
figure, axisList = plt.subplots(len(plotNames), sharex=True, sharey=True)
tempDF = pd.DataFrame()
tempDF['date'] = pd.date_range('2015-01-01','2015-12-31',freq='D')
tempDF['value'] = np.random.randn(tempDF['date'].size)
tempDF['value2'] = np.random.randn(tempDF['date'].size)
for i in range(len(plotNames)):
axisList[i].plot_date(tempDF['date'],tempDF['value'],'b-',xdate=True)
# 2. Create a new single axis in the figure. This new axis sits over
# the top of the axes drawn previously. Make all the components of
# the new single axis invisibe except for the x and y labels.
big_ax = figure.add_subplot(111)
big_ax.set_axis_bgcolor('none')
big_ax.set_xlabel('Date',fontweight='bold')
big_ax.set_ylabel('Random normal',fontweight='bold')
big_ax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')
big_ax.spines['right'].set_visible(False)
big_ax.spines['top'].set_visible(False)
big_ax.spines['left'].set_visible(False)
big_ax.spines['bottom'].set_visible(False)
# 3. Plot a separate figure
# =========================
figure2,ax2 = plt.subplots()
ax2.plot_date(tempDF['date'],tempDF['value2'],'-',xdate=True,color='green')
ax2.set_xlabel('Date',fontweight='bold')
ax2.set_ylabel('Random normal',fontweight='bold')
# Save plot
# =========
plt.savefig('tempPlot.png',dpi=300)
基本上,绘制全图的基本原理如下:
- 创建第一个图形并使用循环绘制 3 个单独的轴
- 在同一图形中绘制单个轴以位于图形顶部 之前画的。标记 x 和 y 轴。使所有其他方面 此轴不可见。
- 创建第二个图形并在单个轴上绘制数据。
使用 jupyter-notebook 时,该图的显示方式与我想要的一样,但是保存该图时,该文件仅包含第二个图形。
我的印象是绘图可以有多个图形,并且图形可以有多个轴。但是,我怀疑我对图、子图、图形和轴之间的差异存在根本性的误解。有人可以解释我做错了什么并解释如何将整个图像保存到单个文件中。
【问题讨论】:
-
我认为当您调用 plt.savefig 时,它会抓取当前图形并绘制它。
-
figure.savefig('figure1.png')将保存第一个数字,figure2.savefig('figure2.png')将保存第二个数字。 -
所以,我想我只需要一个可以保存到单个文件中的图形。是否可以将前 3 个(蓝色)轴分组为图形的单个区域,而将底部(绿色)轴作为第二个不同的区域?
标签: pandas matplotlib