熊猫图栏:其他列的图例显示在图中

时间:2018-10-27 04:23:04

标签: pandas matplotlib legend

我有以下代码,并在jupyter上运行。

# Make the 4 plots:
import matplotlib.pyplot as plt
# Dwell Time
ax = hour_17['Average Dwell Time'].plot(kind='bar', figsize=(15, 10), 
legend=True, fontsize=12)
ax.set_xlabel("5-minutes interval between 17:00-18:00", fontsize=12)
ax.set_ylabel("Time (sec)", fontsize=12)
plt.savefig('name1.jpeg')

# Waiting Time
ax = hour_17['Average Waiting Time'].plot(kind='bar', figsize=(15, 10), 
legend=True, fontsize=12)
ax.set_xlabel("5-minutes interval between 17:00-18:00", fontsize=12)
ax.set_ylabel("Time (sec)", fontsize=12)
plt.savefig('name2.jpeg')

存在以下问题: 第一个图显示指示的列和图例,而第二个图包含两个图例:平均等待时间和平均停留时间,并显示与第一个图相同的信息。 实际上,我必须从4列中绘制数据,因此最后一个图包含4个图例。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您在代码中所做的就是将两个图的图数据存储到ax,因此会产生额外的图例。理想情况下,您想使用plt.subplots()编码样式来防止这种情况。您有两种选择:

  1. 将斧头重命名为其他名称(也许是斧头2)以等待时间。
  2. 使用plt.subplots()初始化一个单独的图

第三个选项是根本不使用fig,ax样式,而是直接使用plt.plot方法。关于为什么这是一个坏主意有很多讨论。 This post解释了方法上的差异。

如果要进行两个单独的绘图,请使用下面的单个绘图方法,只需两次即可。如果要合并绘图,可以使用第二种方法。这来自matplotlib文档here

#Creates just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

#Creates two subplots and unpacks the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
相关问题