直接从pandas绘图时,有没有一种方法可以抑制图例条目?

huangapple go评论83阅读模式
英文:

Is there a way to suppress legend entry when plotting directly from pandas?

问题

我需要在Matplotlib轴ax上执行多个绘图操作。数据存储在一个pandas DataFrame中,因此自然要使用多个绘图命令:

df.plot(..., ax=ax)

但对于其中一些情况,我不想在图例中显示标签。我尝试添加label="nolegend",但这并不起作用。

我找到的唯一解决方法是首先从DataFrame中提取数据,然后在循环中使用单独的ax.plot命令绘制它们,并在需要时添加label参数到图例中。这很繁琐。

注意:我不是在问如何完全删除图例。

编辑:在@Vitalizzare发布了他的不错回答之后(谢谢!):当然,我尝试过了,因为这在文档中提到过,但在我的情况下它不起作用。很难理解为什么,但我认为它与绘制的曲线数量有关。考虑以下代码:

dg = pd.DataFrame(data=np.random.rand(400).reshape(10,40))
fig1, ax = plt.subplots(figsize=(12, 4))
dg.iloc[1:8].plot(ax=ax,style='.-',color='lightgray',legend=False)
dg[[32,33]].iloc[1:8].plot(ax=ax)

这里发生了一些非常奇怪的事情。我得到了不一致的结果!有时候我得到的图没有图例。我不知道为什么。我正在运行mpl 3.5.1和pandas 1.4.2。在我的原始笔记本中,我无法获得正确的行为。

英文:

I need to do multiple plot operations on a Matplotlib axis ax. The data are in a pandas DataFrame, so it is natural to use multiple plotting commands:

df.plot(..., ax=ax)

But for some of those, I don't want a label entry in the legend. I have tried to add label="_nolegend_" but that does not work.

The only workaround I found is to first extract the data from the DataFrame, then plot them in a loop with individual ax.plot commands, adding a label parameter where I want it in the legend. This is tedious.

NOTE: I am not asking how to remove the legend altogether.

EDIT: After @Vitalizzare posted his nice answer (thank you!): Of course, I tried that because it's in the documentation, but it does not work in my case. It isn't easy to understand why, but I think it has to do with the number of curves plotted. Consider this code:

dg = pd.DataFrame(data=np.random.rand(400).reshape(10,40))
fig1, ax = plt.subplots(figsize=(12, 4))
dg.iloc[1:8].plot(ax=ax,style='.-',color='lightgray',legend=False)
dg[[32,33]].iloc[1:8].plot(ax=ax)

Something very strange happens here. I get inconsistent results! Sometimes I get a figure with NO legend. I have no idea why. I am running mpl 3.5.1 and pandas 1.4.2. In my original notebook, I cannot get the correct behavior.

答案1

得分: 1

为了避免绘制图例,我们可以将legend=False作为参数传递给df.plot。要将图例限制为前N个标签,我们可以运行ax.legend(list_of_labels_to_show)。要显示任意一组标签,我们可以在同一坐标轴上分两步绘制数据,对于不应显示的部分,使用legend=False

示例:

df = pd.DataFrame({
    'x': [1,2],
    'y': [2,1],
    'z': [1.5,1.5]
})

fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, subplot_kw={'aspect':'equal'}, figsize=(12, 3))

fig.suptitle('绘制数据示例')

ax1.set_title('完整图例')
df.plot(ax=ax1)

ax2.set_title('前N个图例')
df.plot(ax=ax2)
ax2.legend(df.columns[:2])

ax3.set_title('选定的图例')
df[['x','z']].plot(ax=ax3)
df['y'].plot(ax=ax3, legend=False)

ax4.set_title('无图例')
df.plot(ax=ax4, legend=False)

fig.savefig('legend_example.png')

输出:

直接从pandas绘图时,有没有一种方法可以抑制图例条目?

英文:

To avoid plotting a legend we can pass legend=False as a parameter to df.plot. To restrict the legend to the first N labels, we can run ax.legend(list_of_labels_to_show). To show an arbitrary set of labels, we can plot the data separately in 2 steps on the same axes with legend=False on those which shouldn't be displayed.

Example:

df = pd.DataFrame({
    'x': [1,2],
    'y': [2,1],
    'z': [1.5,1.5]
})

fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, subplot_kw={'aspect':'equal'}, figsize=(12, 3))

fig.suptitle('Plotting data with')

ax1.set_title('full legend')
df.plot(ax=ax1)

ax2.set_title('first n legend')
df.plot(ax=ax2)
ax2.legend(df.columns[:2])

ax3.set_title('selected legend')
df[['x','z']].plot(ax=ax3)
df['y'].plot(ax=ax3, legend=False)

ax4.set_title('no legend')
df.plot(ax=ax4, legend=False)

fig.savefig('legend_example.png')

Output:

直接从pandas绘图时,有没有一种方法可以抑制图例条目?

huangapple
  • 本文由 发表于 2023年8月5日 11:24:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定