[英]Matplotlib bar chart negative values below x-axis
我是使用 Matplotlib 的新手。 我正在嘗試構建一個圖表,其中的值也可以為負。 使用來自 matplotlib 的通用圖形
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
performance = [10,8,6,-4,2,1]
plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Usage')
plt.title('Programming language usage')
plt.show()
這產生
但是,我想使用 x 軸作為 y=0 線而不是單獨的 y=0。 因此,對於任何負值,它會出現在 x 軸下方,而對於正值,它會出現在 x 軸上方。
它會以某種方式看起來像這樣。
我設法擺脫了 y 軸上的周圍線條和值。 需要知道如何使 x 軸成為 y=0 線。
任何幫助,將不勝感激。
非常感謝你。
從這里開始,通過訪問軸對象並修改spines
是相當簡單的,您只需要首先使用plt.gca()
方法公開Axes
對象。
這里的缺點是獲取 xticklabels 如何放置它們有點棘手,但這只是將相關文本放在Axes
然后對xlabel
重復的xlabel
。 你總是可以嘗試使用plt.xlabel()
的labelpad
參數,但我並沒有真正玩過它。
import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
performance = [10,8,6,-4,2,1]
plt.bar(y_pos, performance, align='center', alpha=0.5)
# Get the axes object
ax = plt.gca()
# remove the existing ticklabels
ax.set_xticklabels([])
# remove the extra tick on the negative bar
ax.set_xticks([idx for (idx, x) in enumerate(performance) if x > 0])
ax.spines["bottom"].set_position(("data", 0))
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
# placing each of the x-axis labels individually
label_offset = 0.5
for language, (x_position, y_position) in zip(objects, enumerate(performance)):
if y_position > 0:
label_y = -label_offset
else:
label_y = y_position - label_offset
ax.text(x_position, label_y, language, ha="center", va="top")
# Placing the x-axis label, note the transformation into `Axes` co-ordinates
# previously data co-ordinates for the x ticklabels
ax.text(0.5, -0.05, "Usage", ha="center", va="top", transform=ax.transAxes)
plt.show()
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.