簡體   English   中英

如何使用數據框創建帶有secondary_y的條形圖

[英]How to create bar chart with secondary_y from dataframe

我想創建一個包含在Pandas數據幀中的兩個系列(比如'A'和'B')的條形圖。 如果我想用不同的y軸繪制它們,我可以使用secondary_y

df = pd.DataFrame(np.random.uniform(size=10).reshape(5,2),columns=['A','B'])
df['A'] = df['A'] * 100
df.plot(secondary_y=['A'])

但是如果我想創建條形圖, 則會忽略等效命令(它不會在y軸上放置不同的比例),因此來自“A”的條形圖很大,以至於無法區分“B”條形圖:

df.plot(kind='bar',secondary_y=['A'])

我怎么能直接在熊貓中做到這一點? 或者你會如何創建這樣的圖表?

我正在使用pandas 0.10.1和matplotlib 1.2.1版。

不要以為熊貓圖表支持這一點。 做了一些手動matplotlib代碼..你可以進一步調整它

import pylab as pl
fig = pl.figure()
ax1 = pl.subplot(111,ylabel='A')
#ax2 = gcf().add_axes(ax1.get_position(), sharex=ax1, frameon=False, ylabel='axes2')
ax2 =ax1.twinx()
ax2.set_ylabel('B')
ax1.bar(df.index,df.A.values, width =0.4, color ='g', align = 'center')
ax2.bar(df.index,df.B.values, width = 0.4, color='r', align = 'edge')
ax1.legend(['A'], loc = 'upper left')
ax2.legend(['B'], loc = 'upper right')
fig.show()

在此輸入圖像描述

我相信有辦法迫使一個酒吧進一步調整它。 將酒吧進一步分開,略微透明等

好吧,我最近遇到了同樣的問題,即使這是一個老問題,我想我可以給出這個問題的答案,以防萬一其他人對此失去了理智。 Joop給出了要做的事情的基礎,當你在數據幀中只有(例如)兩列時很容易,但是當你為兩個軸設置不同數量的列時,它變得非常討厭,因為事實是你需要使用pandas plot()函數的position參數。 在我的例子中,我使用seaborn,但它是選擇性的:

import pandas as pd
import seaborn as sns
import pylab as plt
import numpy as np

df1 = pd.DataFrame(np.array([[i*99 for i in range(11)]]).transpose(), columns = ["100"], index = [i for i in range(11)])
df2 = pd.DataFrame(np.array([[i for i in range(11)], [i*2 for i in range(11)]]).transpose(), columns = ["1", "2"], index = [i for i in range(11)])

fig, ax = plt.subplots()
ax2 = ax.twinx()

# we must define the length of each column. 
df1_len = len(df1.columns.values)
df2_len = len(df2.columns.values)
column_width = 0.8 / (df1_len + df2_len)

# we calculate the position of each column in the plot. This value is based on the position definition :
# Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
# http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.plot.html
df1_posi = 0.5 + (df2_len/float(df1_len)) * 0.5
df2_posi = 0.5 - (df1_len/float(df2_len)) * 0.5

# In order to have nice color, I use the default color palette of seaborn
df1.plot(kind='bar', ax=ax, width=column_width*df1_len, color=sns.color_palette()[:df1_len], position=df1_posi)
df2.plot(kind='bar', ax=ax2, width=column_width*df2_len, color=sns.color_palette()[df1_len:df1_len+df2_len], position=df2_posi)

ax.legend(loc="upper left")

# Pandas add line at x = 0 for each dataframe.
ax.lines[0].set_visible(False)
ax2.lines[0].set_visible(False)

# Specific to seaborn, we have to remove the background line 
ax2.grid(b=False, axis='both')

# We need to add some space, the xlim don't manage the new positions
column_length = (ax2.get_xlim()[1] - abs(ax2.get_xlim()[0])) / float(len(df1.index))
ax2.set_xlim([ax2.get_xlim()[0] - column_length, ax2.get_xlim()[1] + column_length])

fig.patch.set_facecolor('white')
plt.show()

結果: http//i.stack.imgur.com/LZjK8.png

我沒有測試每種可能性,但無論你使用的每個數據幀中的列數是多少,它看起來都能正常工作。

暫無
暫無

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

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