python - matplotlib:改变条的位置
问题描述
我正在尝试在 x 轴上使用 2 个条形图在 matplotlib 中创建条形图子图。我创建了以下图像:
这是使用以下代码创建的:
import pandas as pd
import matplotlib.pyplot as plt
ydata1=pd.Series.from_array([451,505])
ydata2=pd.Series.from_array([839,286])
fig, (ax1, ax2) = plt.subplots(1,2,sharex='col',sharey='row')
xlabels = ['x1', 'x2']
ax1.bar(xlabels,ydata1, 0.4, align='center') #0.4 is width of bar
ax2.bar(xlabels,ydata2, 0.4, align='center')
plt.show()
我遇到的问题是我想调整条的位置,使它们对称并且与每个刻面的边缘等距,而不是在每个刻面的左右边缘(目前是这样)。有什么方法可以调整 matplotlib 中条形的位置,使它们对称?
谢谢
解决方案
要根据条形宽度和条数获得准确的边距,请注意:
- 条的中心在位置
0, 1, ..., N-1
- 两个条之间的距离是
1-bar_width
- 第一个小节开始于
0-bar_width/2
; 要使条形和左边距之间的间距与条形本身之间的间距相等,可以将左边距设置为0-bar_width/2-(1-bar_width)
- 同样,右边距可以设置为
N-1+bar_width/2+(1-bar_width)
import matplotlib.pyplot as plt
import numpy as np
N = 8
ydata1 = np.random.randint(200, 800, N)
ydata2 = np.random.randint(200, 800, N)
fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', sharey='row')
xlabels = [f'x{i}' for i in range(1, N + 1)]
width = 0.4
ax1.bar(xlabels, ydata1, width, align='center')
ax2.bar(xlabels, ydata2, width, align='center')
margin = (1 - width) + width / 2
ax1.set_xlim(-margin, len(xlabels) - 1 + margin)
ax2.set_xlim(-margin, len(xlabels) - 1 + margin)
plt.show()
推荐阅读
- spring - 招摇 2.6.1 /swagger-resources/configuration/ui 404
- javascript - React Native CheckBox 和 FlatList:无法切换,并且每个项目只能选择一次
- php - 用于 php 的 ffmpeg 命令无法在实时服务器上运行
- reactjs - 在本机反应中,如何使组件中的功能全局化?
- c - 一次使用不同结构类型的内存分配?(Valgrind 证明)
- asp.net-web-api - C# web api控制器上的后台处理
- c++ - `std::find()` 是否短路?
- ruby-on-rails - 在ruby中特定迁移之前添加迁移的方法是什么
- javascript - 如果只有该属性可用,如何访问 Javascript 对象属性 - ReactJS
- maven - 无法在声纳仪表板上查看所选应用程序的代码覆盖率选项卡