gpt4 book ai didi

python - Pandas df.plot 子图上的多个传说?

转载 作者:太空狗 更新时间:2023-10-29 22:29:22 25 4
gpt4 key购买 nike

我之前曾问过一个问题,关于如何在此处的单独子图上绘制 pandas 数据框中的不同列:Plot multiple lines on subplots with pandas df.plot ,并得到了很好的答案。现在我正试图最大限度地利用情节上的空间,而传说被证明是一个问题。我想要做的是将 3 或 4 个系列放在一个图例上,将其余系列放在另一个图例上,这样我就可以将每个系列放在一个角落里,它们会很好地适合。

我尝试使用为 matplotlib 描述的方法,如下所示:

from matplotlib.pyplot import *

p1, = plot([1,2,3], label="test1")
p2, = plot([3,2,1], label="test2")

l1 = legend([p1], ["Label 1"], loc=1)
l2 = legend([p2], ["Label 2"], loc=4) # this removes l1 from the axes.
gca().add_artist(l1) # add l1 as a separate artist to the axes

show()

但是,我遇到的问题要么来自使用 pandas df.plot,要么来自尝试在子图中实现。这是我尝试过的:

f, (ax1, ax2) = plt.subplots(ncols = 2)

p1 = dfcomb.iloc[:,:3].plot(ax=ax1, figsize=(14,5))
p2 = dfcomb.iloc[:,3:6].plot(ax=ax1, figsize=(14,5))
l1 = ax1.legend([p1], ["Label 1"], loc=1)
l2 = ax1.legend([p2], ["Label 2"], loc=4) # this removes l1 from the axes.
gca().add_artist(l1) # add l1 as a separate artist to the axes

这是我得到的:

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-108-d3206d8ce17d> in <module>()
15 l1 = ax1.legend([p1], ["Label 1"], loc=1)
16 l2 = ax1.legend([p2], ["Label 2"], loc=4) # this removes l1 from the axes.
---> 17 gca().add_artist(l1)
18
19 ax1.set_xlabel('Suction (cm)')

C:\Anaconda\lib\site-packages\matplotlib\axes\_base.pyc in add_artist(self, a)
1646 Returns the artist.
1647 """
-> 1648 a.axes = self
1649 self.artists.append(a)
1650 self._set_artist_props(a)

C:\Anaconda\lib\site-packages\matplotlib\artist.pyc in axes(self, new_axes)
235 if (new_axes is not None and
236 (self._axes is not None and new_axes != self._axes)):
--> 237 raise ValueError("Can not reset the axes. You are "
238 "probably trying to re-use an artist "
239 "in more than one Axes which is not "

ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported

有人有解决方法吗?

最佳答案

您被对 gca() 的性质的错误假设埋伏了.我也很惊讶,这就是为什么我决定添加一个答案(否则我们主要是在谈论拼写错误问题)。另外,我注意到这个问题与 Pandas 无关。

这是一个没有 pandas 的重现问题的最小示例:

import matplotlib.pyplot as plt

f, (ax1, ax2) = plt.subplots(ncols = 2)
p1, = ax1.plot([1,2,3], label="test1")
p2, = ax1.plot([3,2,1], label="test2")

l1 = ax1.legend([p1], ["Label 1"], loc=1)
l2 = ax1.legend([p2], ["Label 2"], loc=4) # this removes l1 from the axes.
plt.gca().add_artist(l1)

那么问题是什么?仔细查看错误消息:

ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported

(强调我的)。看:

>>> ax1
<matplotlib.axes._subplots.AxesSubplot at 0x7fd83abf7e10>
>>> ax2
<matplotlib.axes._subplots.AxesSubplot at 0x7fd83a992850>
>>> plt.gca()
<matplotlib.axes._subplots.AxesSubplot at 0x7fd83a992850>

问题是,即使您正在处理 ax1 ,“图形当前轴”又名 gca()指向 ax2 , Axes最新创建。

现在解决方案很简单:显式调用重绘(记住,显式优于隐式):

import matplotlib.pyplot as plt

f, (ax1, ax2) = plt.subplots(ncols = 2)
p1, = ax1.plot([1,2,3], label="test1")
p2, = ax1.plot([3,2,1], label="test2")

l1 = ax1.legend([p1], ["Label 1"], loc=1)
l2 = ax1.legend([p2], ["Label 2"], loc=4) # this removes l1 from the axes.
ax1.add_artist(l1) # <-- just change here, refer to ax1 explicitly

它还活着!

result


如果你真的想用df.plot (一个方便的功能)而不是控制你自己创建的情节,你必须做更多的工作。遗憾df.plot返回 Axes它绘制到的对象(而不是绘图中包含的线对象列表),因此我们需要查看 Axes 的子对象为了找到情节。上面的示例使用数据框:

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

# example input
df1 = pd.DataFrame({'test1': [1,2,3]})
df2 = pd.DataFrame({'test2': [3,2,1]})

f, (ax1, ax2) = plt.subplots(ncols = 2)
# disable automatic legends in order two have two separate legends
df1.plot(ax=ax1, legend=False)
df2.plot(ax=ax1, legend=False)

# ugly hack to grab the children of the created Axes
p1,p2 = [child for child in ax1.get_children()
if isinstance(child, matplotlib.lines.Line2D)]

# untangling the plots will be harder the more plots there are in the Axes
l1 = ax1.legend([p1], df1.columns, loc=1)
l2 = ax1.legend([p2], df2.columns, loc=4) # this removes l1 from the axes.
ax1.add_artist(l1) # <-- just change here, refer to ax1 explicitly

关于python - Pandas df.plot 子图上的多个传说?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37624012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com