2017-04-21 244 views
0

我想繪製matplotlib條形圖,左邊是一個y軸,右邊是另一個共同的x軸。範圍欄打開x軸。 Perc列位於左側y軸,計數列位於右側y軸。請告知如何繼續。Matplotlib條形圖與兩個Y軸和公共X軸

的樣本數據是在這裏 - SampleFileHere

enter image description here

import numpy as np 
import pandas as pd 
import seaborn as sbn 
import matplotlib.pyplot as plt 


fig = plt.figure() 
ax = td['perc'].plot(kind="bar", alpha=0.7) 
plt.xticks(td['ranges'].tolist()) 
ax2 = ax.twinx() 
ax2.plot(ax.get_xticks(),td['count'],marker='o', c='navy', linewidth=4) 

我得到下面的錯誤。

<ipython-input-24-c1d398c0d012> in <module>() 
     7 fig = plt.figure() 
     8 ax = td['perc'].plot(kind="bar", alpha=0.7) 
----> 9 plt.xticks(td['ranges'].tolist()) 
    10 ax2 = ax.twinx() 
    11 ax2.plot(ax.get_xticks(),td['count'],marker='o', c='navy', linewidth=4) 
+0

我想提供一個鏈接到Excel。請暫停 。我只是在搜索如何去做 – Harish

+0

已經提供了鏈接到數據 – Harish

回答

0

您不能將xticks設置爲某些非數字值。相反,您需要將xticklabels設置爲「範圍」列中的條目。

import numpy as np 
import pandas as pd 
import seaborn as sns 
import matplotlib.pyplot as plt 

counts = np.array([56000,900,5000,6000,30000,3500,300]).astype(float) 
perc = counts/counts.sum() 
df = pd.DataFrame({"range": list("ABCDEFG"),"count":counts, "perc":perc}) 

fig = plt.figure() 
ax = df['perc'].plot(kind="bar", alpha=0.7) 

ax2 = ax.twinx() 
ax2.plot(ax.get_xticks(),df['count'],marker='o', c='navy', linewidth=4) 

ax.set_xticklabels(df['range']) 
ax.set_ylim(0,1.3*df["perc"].max()) 
ax2.set_ylim(0,1.3*df["count"].max()) 
ax2.grid(False) 
plt.show() 

enter image description here