matplotlib - 如何在使用 plt.vlines() 创建的条形图中绘制网格
问题描述
我想在 python 中创建一个条形图。我希望这个情节很漂亮,但我不喜欢 pythonaxes.bar()
函数的外观。因此,我决定使用plt.vlines()
. 这里的挑战是我的 x-data 是一个包含字符串而不是数字数据的列表。当我绘制图表时,两列之间的间距(在我的示例中,列 2 = 0)非常大:
此外,我想要一个网格。但是,我也希望有较小的网格线。如果我的数据是数字的,我知道如何获得所有这些。但由于我的 x-data 包含字符串,我不知道如何设置 x_max。有什么建议么?
解决方案
在内部,标签的位置编号为 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()
推荐阅读
- php - 使用imagick php转换PDF多页创建双文件
- php - 控制器中的第二种方法不起作用 PHP MVC
- bash - 如何使用 grep/awk/sed 在分隔符之间隔离文件的一部分,可能会交叉线
- c# - 我无法使用矩阵容器打印名称是否有可能使用矩阵打印名称?
- css - kendo ui 角度拆分面板更改背景颜色
- couchdb - 文档架构性能
- virtual-reality - 使用谷歌纸板在 VR 模式下 A-Frame 光标不移动
- python - 3d 内核和 3d 图像(说 RGB)的矩阵乘法究竟是如何发生的以提供 2d 输出?
- ruby-on-rails - 当我尝试从 ruby on rails 应用程序链接 twitter 时出现 500 内部服务器错误
- javascript - Google App Engine:修改 Cloud Run 环境