首页 > 解决方案 > 如何在使用 plt.vlines() 创建的条形图中绘制网格

问题描述

我想在 python 中创建一个条形图。我希望这个情节很漂亮,但我不喜欢 pythonaxes.bar()函数的外观。因此,我决定使用plt.vlines(). 这里的挑战是我的 x-data 是一个包含字符串而不是数字数据的列表。当我绘制图表时,两列之间的间距(在我的示例中,列 2 = 0)非常大:

在此处输入图像描述

此外,我想要一个网格。但是,我也希望有较小的网格线。如果我的数据是数字的,我知道如何获得所有这些。但由于我的 x-data 包含字符串,我不知道如何设置 x_max。有什么建议么?

标签: matplotlib

解决方案


在内部,标签的位置编号为 0,1,... 因此,将 x 限制设置在 0 之前和最后一个之后,会使它们更加居中。

通常,条形图的“脚”在地面上,可以通过设置plt.ylim(0, ...)。次要刻度可以定位在例如 0.2 的倍数处。将刻度的长度设置为零可以计算网格的位置,但会抑制刻度线。

from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np

labels = ['Test 1', 'Test 2']
values = [1, 0.7]

fig, ax = plt.subplots()
plt.vlines(labels, 0, values, colors='dodgerblue', alpha=.4, lw=7)

plt.xlim(-0.5, len(labels) - 0.5)  # add some padding left and right of the bars
plt.ylim(0, 1.1)  # bars usually have their 0 at the bottom

ax.xaxis.set_minor_locator(MultipleLocator(.2))
plt.tick_params(axis='x', which='both', length=0) # ticks not shown, but position serves for gridlines
plt.grid(axis='both', which='both', ls=':') # optionally set the linestyle of the grid

plt.show()

结果图


推荐阅读