熊猫:Bar-Plot有两个条和两个y轴

tim*_*tim 30 python plot matplotlib pandas

我有一个看起来像这样的DataFrame:

     amount     price
age
A     40929   4066443
B     93904   9611272
C    188349  19360005
D    248438  24335536
E    205622  18888604
F    140173  12580900
G     76243   6751731
H     36859   3418329
I     29304   2758928
J     39768   3201269
K     30350   2867059
Run Code Online (Sandbox Code Playgroud)

现在我想绘制一个条形图,其中x轴上的年龄作为标签.对于每个x-tick,应该有两个柱,一个柱用于金额,一个用于价格.我可以通过简单地使用它来实现这一点:

df.plot(kind='bar')
Run Code Online (Sandbox Code Playgroud)

问题是缩放.价格高得多,我无法确定该图表中的金额,请参阅:

在此输入图像描述

因此,我想要第二个y轴.我尝试使用:

df.loc[:,'amount'].plot(kind='bar')
df.loc[:,'price'].plot(kind='bar',secondary_y=True)
Run Code Online (Sandbox Code Playgroud)

但这只是覆盖了条形并没有将它们并排放置.有没有办法做到这一点,而无需访问较低级别的matplotlib(这显然可以通过手动并排放置条)?

现在,我在子图中使用了两个单独的图:

df.plot(kind='bar',grid=True,subplots=True,sharex=True); 
Run Code Online (Sandbox Code Playgroud)

导致:

在此输入图像描述

Ffi*_*ydd 61

使用新的pandas版本(0.14.0或更高版本),以下代码将起作用.为了创建两个轴,我手动创建了两个matplotlib轴对象(axax2),它们将用于两个条形图.

绘制Dataframe时,您可以选择使用的轴对象ax=....另外,为了防止两个图重叠,我修改了它们与position关键字参数对齐的位置,这默认为0.5但这意味着两个条形图重叠.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from io import StringIO

s = StringIO("""     amount     price
A     40929   4066443
B     93904   9611272
C    188349  19360005
D    248438  24335536
E    205622  18888604
F    140173  12580900
G     76243   6751731
H     36859   3418329
I     29304   2758928
J     39768   3201269
K     30350   2867059""")

df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True)

fig = plt.figure() # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

width = 0.4

df.amount.plot(kind='bar', color='red', ax=ax, width=width, position=1)
df.price.plot(kind='bar', color='blue', ax=ax2, width=width, position=0)

ax.set_ylabel('Amount')
ax2.set_ylabel('Price')

plt.show()
Run Code Online (Sandbox Code Playgroud)

情节

  • 这很棒.但这个传说只出现在蓝色而不是两者之间. (3认同)
  • 你好。“fig.add_subplot()”中的“111”参数是什么意思? (2认同)

InL*_*Law 40

你只需要写:df.plot(kind ='bar' ,secondary_y ='amount')

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from io import StringIO
s = StringIO("""     amount     price
A     40929   4066443
B     93904   9611272
C    188349  19360005
D    248438  24335536
E    205622  18888604
F    140173  12580900
G     76243   6751731
H     36859   3418329
I     29304   2758928
J     39768   3201269
K     30350   2867059""")
df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True)

_ = df.plot( kind= 'bar' , secondary_y= 'amount' , rot= 0 )
plt.show()
Run Code Online (Sandbox Code Playgroud)

Secondary_Y_axis

  • `secondary_y` 的语义有点出乎意料。如果你想在左边绘制 A、B 和在右边绘制 C,你必须说 `df.plot(y=['A', 'B', 'C'], secondary_y=['C']) ` 而不是 `df.plot(y=['A', 'B'], secondary_y=['C'])`。当然,如果 `df` 只有那 3 列,你可以不指定 `y`。 (7认同)
  • 这个答案应该有更多的选票. (4认同)

HYR*_*YRY 7

这是另一种方法:

  • 在左轴创建所有条形
  • 通过更改它的transform属性将一些条移动到右轴

这是代码:

import pylab as pl
df = pd.DataFrame(np.random.rand(10, 2), columns=["left", "right"])
df["left"] *= 100

ax = df.plot(kind="bar")
ax2 = ax.twinx()
for r in ax.patches[len(df):]:
    r.set_transform(ax2.transData)
ax2.set_ylim(0, 2);
Run Code Online (Sandbox Code Playgroud)

这是输出:

在此输入图像描述


Tho*_* G. 6

正如 InLaw 所提到的,你应该使用secondary_y = 'amount'

在这里添加他的答案是如何设置两个轴的ylabels :

df.plot.bar(figsize=(15,5), secondary_y= 'amount')

ax1, ax2 = plt.gcf().get_axes() # gets the current figure and then the axes

ax1.set_ylabel('price')

ax2.set_ylabel('amount')
Run Code Online (Sandbox Code Playgroud)