簡體   English   中英

關於Pandas df.plot子圖的多個傳說?

[英]Multiple Legends on Pandas df.plot subplots?

之前我曾經問過一個關於如何在不同的子圖上繪制熊貓數據框中的不同列的問題: 用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()性質的錯誤假設遭到了伏擊。 我也很驚訝,這就是為什么我決定添加一個答案(否則我們主要談論一個錯字級別的問題)。 另外,我注意到這個問題與熊貓無關。

這是一個在沒有熊貓的情況下重現你的問題的最小例子:

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:無法重置軸。 您可能正在嘗試在多個不受支持的Axes中重復使用藝術家

(強調我的)。 看:

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

問題在於,即使您正在使用ax1 ,“圖形當前軸”也稱為gca()指向ax2Axes最新創建。

解決方案現在很簡單:使用重繪調用顯式 (請記住, 顯式優於隱式 ):

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

它還活着!

結果


如果你真的想使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM