【问题标题】:Pandas plot bar: legends of other columns appears in plot熊猫情节栏:情节中出现其他列的图例
【发布时间】:2019-03-31 19:15:12
【问题描述】:

我有以下代码并在 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 个图例。

知道发生了什么吗?谢谢!

【问题讨论】:

    标签: pandas matplotlib legend


    【解决方案1】:

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

    1. 将 ax 重命名为其他名称(可能是 ax2)以等待时间。
    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)
    

    【讨论】:

    • 也许标记解决方案?这样,如果其他人有类似的解决方案,他们就可以找到它。我很高兴它成功了!
    • 我是新用户,没有权限标记!
    猜你喜欢
    • 2021-11-25
    • 2017-04-12
    • 1970-01-01
    • 2021-12-26
    • 2016-03-24
    • 2016-11-15
    • 2018-09-06
    • 2021-08-09
    • 2021-11-03
    相关资源
    最近更新 更多