python - 当图形大小更改时,Matplotlib 给出错误的刻度标签值

标签 python matplotlib

我使用以下代码来绘制 matplotlib 堆栈图:

mpl.rcdefaults()

fig, ax = plt.subplots()
years = [1980, 1990, 2000, 2010, 2020]
data = [
    [10000, 11000, 12000, 13000, 11000], [20000, 21000, 31000, 61000, 65000],
    [0, 10000, 30000, 100000, 90000]]

 ax.stackplot(years, data)

ax.grid(linestyle='--', color='k', alpha=0.15, axis='y')
ax.set_yticklabels([x / 1000 for x in ax.get_yticks()])

width = 6
height = width/1.6

fig.set_size_inches(width, height)

这将创建以下图表,并带有正确的 y 轴标签: stackplot

但是,当我使用 width = 4 更改绘图的大小时,我得到以下图表,其中 y 刻度值似乎由于某种原因减半:

stack plot with the y tick labels showing half the value they should be

什么给出了?

干杯!

最佳答案

问题是,调整大小后,yticks 是不同的,因此您会得到更大的一组标签,但它们并不真正适合。调整大小后需要设置标签。正如您所看到的,调整大小后的图只有四个刻度。调整大小之前绘图的前四个刻度标签显示在输出中,这是不正确的。

为了便于解释,我在调整大小之前和之后保留了 tickticklabelsprint()

import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rcdefaults()

fig, ax = plt.subplots()

years = [1980, 1990, 2000, 2010, 2020]
data = [
    [10000, 11000, 12000, 13000, 11000], [20000, 21000, 31000, 61000, 65000],
    [0, 10000, 30000, 100000, 90000]]

ax.stackplot(years, data)
ax.grid(linestyle='--', color='k', alpha=0.15, axis='y')
print("Ticks before:",list(ax.get_yticks()))
width = 4
height = width/1.6
fig.set_size_inches(width, height)
ax.set_yticklabels([x/1000 for x in ax.get_yticks()])
print("Ticks after:",list(ax.get_yticks()))
plt.show()

输出:

enter image description here

关于python - 当图形大小更改时,Matplotlib 给出错误的刻度标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50395392/

相关文章:

python - 在二叉搜索树的中序遍历中,它在代码中的哪个位置向上遍历?

python - 通过使用 pandas 对列进行分组来汇总数据框

python - Matplotlib 中的 MonthLocator

matplotlib - 如何删除 FancyArrowPatch 的箭头尖端和目标点之间的空白?

matplotlib - 在双轴上调整刻度标签大小

python - matplotlib 中图像中的标签问题

python - 在 python 中打印混淆矩阵的精度

python - 字典键的Javascript样式点符号unpythonic?

python - 将函数映射和参数存储在字典中

python - matplotlib 的 savefig() 不能使用读写文件?