【发布时间】:2020-07-25 00:34:23
【问题描述】:
基于 matplotlib 中的以下示例,我制作了一个函数,将两个每周时间序列绘制为并排条形图。 https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py
我的问题是我明确设置了 xtick,这会创建混乱的 xtick-labels。有没有办法让 matplotlib 在这样的图中明确选择 xticks(位置和标签)?
我必须说,我发现使用 (x - width/2) 指定条形位置的整个操作对于并排条形来说非常不雅 - 还有其他选项(除了 matplotlib 或其他包之外的其他包matplotlib 中的规范)以避免编写此类显式代码?
下面是代码和结果。我正在寻找一种解决方案,可以选择 xticks 和 xticklabels 的数量和位置,使其可读:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
labels = ['W1-2020', 'W2-2020', 'W3-2020', 'W4-2020', 'W5-2020','W6-2020','W7-2020','W8-2020','W9-2020','W10-2020','W11-2020','W12-2020','W13-2020','W14-2020','W15-2020']
men_means = [20, 34, 30, 35, 27,18,23,29,27,29,38,28,17,28,23]
women_means = [25, 32, 34, 20, 25,27,18,23,29,27,29,38,19,20, 34]
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()
【问题讨论】:
标签: python matplotlib