python - 使用 matplotlib 在 python 中使用字典的条形图

标签 python matplotlib charts

我有两个字典:

A = {2018: 23, 2019: 30}
B = {2018: 26, 2019:35} 

现在我想绘制 A 和 B 2018/2019 年的趋势。但是在绘制条形图时,我得到以下结果。岁月不断膨胀,填满了空间,b 完全隐藏了 A。请建议如何绘制图表。

enter image description here

原始数据具有数学、科学和总计的平均分,我想将其绘制在同一个图表(条形图)上两年以显示趋势。

最佳答案

您可以将条形图的条形靠右边缘的左侧对齐(传递负宽度以使用右边缘对齐) - 这样您就可以获得并排的条形。或者,您可以堆叠这些条。

这是带有输出的代码:

import matplotlib.pyplot as plt

A = {2018: 23, 2019:30}
B = {2018: 26, 2019:35}

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12,5))

ax1.bar(A.keys(), A.values(), width=0.2, align='edge', label='A')
ax1.bar(B.keys(), B.values(), width=-0.2, align='edge', label='B')
ax1.set_xticks([2018, 2019])
ax1.set_xlabel('YEAR')
ax1.legend()

ax2.bar(A.keys(), A.values(), width=0.4, align='center', label='A')
ax2.bar(B.keys(), B.values(), bottom=[A[i] for i in B.keys()], width=0.4, align='center', label='B')
ax2.set_xticks([2018, 2019])
ax2.set_xlabel('YEAR')
ax2.legend()

fig.show()

enter image description here

编辑:如果您开始处理更多数据,那么使用可以更轻松地处理数据的包是有意义的。 Pandas是一个很棒的软件包,可以为您做到这一点。

这里是一个包含 4 组时间序列数据的示例:

import matplotlib.pyplot as plt
import pandas as pd

A = {2018: 23, 2019:30}
B = {2018: 26, 2019:35}
C = {2018: 30, 2019:40}
D = {2018: 20, 2019:50}

df = pd.DataFrame([A,B,C,D], index=['A','B','C','D']).transpose()

fig, ax= plt.subplots(1,1, figsize=(6,5))

df.plot.bar(ax=ax)
ax.set_xlabel('YEAR')

fig.tight_layout()
fig.show()

输出如下图: enter image description here

关于python - 使用 matplotlib 在 python 中使用字典的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51130673/

相关文章:

python - Windows virtualenv 不为 django 切换 python

python - int 列的奇怪最大最小结果

iphone - 在不使用 Core Plot 库的情况下绘制折线图

javascript - 带文本的 Highcharts 气泡

javascript - 如何在我刚刚使用 jQuery 附加的新元素中创建 google-chart?

python - python中的列中的前三个最大值

python - 如何使用 Python 多处理和 memory_profiler 分析多个子进程?

python - 如何插入大正斜杠来标记 matplotlib 轴

python - 在 Python 中绘制微分方程系统

python-3.x - Matplotlib 导入错误(需要 str、bytes 或 os.PathLike 对象,而不是 PosixPath)