简体   繁体   English

如何在 Python 中将直方图的 y 轴值乘以固定数字

[英]How to multiply the y-axis values of a histogram by a fixed number in Python

I have a list of data to plot using histograms.我有一个要使用直方图绘制的数据列表。 I want to scale the y-axis of each plot separately.我想分别缩放每个图的y-axis If I do like the following, it scales each plot's y-axis by 10.如果我喜欢以下内容,它将每个图的y-axis缩放 10。

protocols = {}
types = {"data1": "data1.csv", "data2": "data2.csv", "data3": "data3.csv"}

for protname, values in protocols.items():
    fig, ax1 = plt.subplots()
    ax1.hist(values["col_data"], facecolor='blue', alpha=0.9, label=protname,align='left')
    y_vals = ax1.get_yticks()
    ax1.set_yticklabels(['{:3.0f}'.format(x * 10) for x in y_vals])
    plt.legend()
    plt.show()

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

However, I want the scaling to be separate for each histogram.但是,我希望每个直方图的缩放都是分开的。 I tried it as the following but it doesn't seem to be working as intended.我按以下方式进行了尝试,但似乎没有按预期工作。

for protname, values in protocols.items():
    fig, ax1 = plt.subplots()
    ax1.hist(values["col_data"], facecolor='blue', alpha=0.9, label=protname,align='left')
    y_vals = ax1.get_yticks()
    ax1.set_yticklabels(['{:3.0f}'.format(x * 10) for x in y_vals if protname=="data1" and ['{:3.0f}'.format(x * 10) for x in y_vals if protname=="data2" and ['{:3.0f}'.format(x * 15) for x in y_vals if protname=="data3"]]])

    plt.legend()
    plt.show()

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

If we try ONLY for one plot as ax1.set_yticklabels(['{:3.0f}'.format(x * 10) for x in y_vals if protname=="data2"]) it applies the changes only to the second plot and leave the others blank.如果我们仅尝试将一个图作为ax1.set_yticklabels(['{:3.0f}'.format(x * 10) for x in y_vals if protname=="data2"])它将更改仅应用于第二个图并且将其他人留空。

At first I'd be interested in why you want to manipulate the y-axis values, as the histogram values are those of your data - I don't see a reason for changing it without loosing the meaning for your data.起初,我对您为什么要操作 y 轴值感兴趣,因为直方图值是您的数据的值 - 我没有看到在不失去数据含义的情况下更改它的理由。

That said, my next question would be generally if you intentionally set plt.subplots inside your for-loop, because one use case for this command is in fact creating several subplots into one figure - perhaps you'll think about that later...也就是说,我的下一个问题通常是您是否有意for 循环中设置plt.subplots ,因为此命令的一个用例实际上是将多个子图创建为一个图形 - 也许您稍后会考虑...

However, the easiest way to apply different factors at different iterations is simply to add them as another list into your loop with zip :但是,在不同的迭代中应用不同因素的最简单方法是使用zip将它们作为另一个列表添加到循环中:

factors = [10, 10, 15]
for (protname, values), m in zip(protocols.items(), factors):
    ...
    ax1.set_yticklabels(['{:3.0f}'.format(x * m) for x in y_vals])
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM