我正在通過Think Stats,我想直觀地比較多個數據集。從書中的例子中我可以看到,通過使用本書作者提供的模塊,可以爲每個數據集生成不同顏色的交錯條形圖,如何在pyplot
中獲得相同的結果?在matplotlib.pyplot中,如何使用交錯條形圖繪製兩個數據集?
感謝
Tunnuz
我正在通過Think Stats,我想直觀地比較多個數據集。從書中的例子中我可以看到,通過使用本書作者提供的模塊,可以爲每個數據集生成不同顏色的交錯條形圖,如何在pyplot
中獲得相同的結果?在matplotlib.pyplot中,如何使用交錯條形圖繪製兩個數據集?
感謝
Tunnuz
呼叫酒吧功能多次,每一個系列。您可以使用左側參數控制條的左側位置,並且可以使用它來防止重疊。
完全未經測試的代碼:
pyplot.bar(numpy.arange(10) * 2, data1, color = 'red')
pyplot.bar(numpy.arange(10) * 2 + 1, data2, color = 'red')
數據2將被吸引偏移了的權利相比於數據的一個將被繪製。
還有的文檔中提供了光輝的榜樣/演示:
http://matplotlib.sourceforge.net/examples/api/barchart_demo.html
Hi @ db42,我該如何添加多個'xlabels',一個用於演示中的2個系列? – 2016-09-07 17:28:02
我碰到這個問題前一段時間來創造一個包裝函數,它接受一個二維數組,並自動創建從多條形圖它:
代碼:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import operator as o
import numpy as np
dpoints = np.array([['rosetta', '1mfq', 9.97],
['rosetta', '1gid', 27.31],
['rosetta', '1y26', 5.77],
['rnacomposer', '1mfq', 5.55],
['rnacomposer', '1gid', 37.74],
['rnacomposer', '1y26', 5.77],
['random', '1mfq', 10.32],
['random', '1gid', 31.46],
['random', '1y26', 18.16]])
fig = plt.figure()
ax = fig.add_subplot(111)
def barplot(ax, dpoints):
'''
Create a barchart for data across different categories with
multiple conditions for each category.
@param ax: The plotting axes from matplotlib.
@param dpoints: The data set as an (n, 3) numpy array
'''
# Aggregate the conditions and the categories according to their
# mean values
conditions = [(c, np.mean(dpoints[dpoints[:,0] == c][:,2].astype(float)))
for c in np.unique(dpoints[:,0])]
categories = [(c, np.mean(dpoints[dpoints[:,1] == c][:,2].astype(float)))
for c in np.unique(dpoints[:,1])]
# sort the conditions, categories and data so that the bars in
# the plot will be ordered by category and condition
conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))]
categories = [c[0] for c in sorted(categories, key=o.itemgetter(1))]
dpoints = np.array(sorted(dpoints, key=lambda x: categories.index(x[1])))
# the space between each set of bars
space = 0.3
n = len(conditions)
width = (1 - space)/(len(conditions))
# Create a set of bars at each position
for i,cond in enumerate(conditions):
indeces = range(1, len(categories)+1)
vals = dpoints[dpoints[:,0] == cond][:,2].astype(np.float)
pos = [j - (1 - space)/2. + i * width for j in indeces]
ax.bar(pos, vals, width=width, label=cond,
color=cm.Accent(float(i)/n))
# Set the x-axis tick labels to be equal to the categories
ax.set_xticks(indeces)
ax.set_xticklabels(categories)
plt.setp(plt.xticks()[1], rotation=90)
# Add the axis labels
ax.set_ylabel("RMSD")
ax.set_xlabel("Structure")
# Add a legend
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], loc='upper left')
barplot(ax, dpoints)
plt.show()
如果您對此功能的功能及其背後的邏輯感興趣,請致電here's a (shamelessly self-promoting) link to the blog post describing it.
嗨,我該如何爲您在這裏出現的3個系列中的每一個添加多個'xlabels'? – 2016-09-07 17:27:34
請您提供有關此解決方案的更多詳細信息? – tunnuz 2011-04-29 16:15:28