joo*_*won 5 python charts axis matplotlib bar-chart
我是使用 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()
Run Code Online (Sandbox Code Playgroud)
这产生
但是,我想使用 x 轴作为 y=0 线而不是单独的 y=0。因此,对于任何负值,它会出现在 x 轴下方,而对于正值,它会出现在 x 轴上方。
它会以某种方式看起来像这样。
我设法摆脱了 y 轴上的周围线条和值。需要知道如何使 x 轴成为 y=0 线。
任何帮助,将不胜感激。
非常感谢你。
小智 7
从这里开始,通过访问轴对象并修改spines
,它相当简单,您只需要Axes
首先使用该plt.gca()
方法公开对象。
这里的缺点是,让你是如何把他们的xticklabels是有点棘手,但仅仅是放置在相关文字的情况下Axes
,然后重复,对于xlabel
。你总是可以尝试使用labelpad
for的参数,plt.xlabel()
但我并没有真正玩过它。
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()
Run Code Online (Sandbox Code Playgroud)
结果:
归档时间: |
|
查看次数: |
3121 次 |
最近记录: |