简体   繁体   English

在轴 matplotlib 上将负值设置为正值以获得百分比

[英]Setting negative values as positive values on axis matplotlib for percentages

I need to make a plot for males and females where the values are in percentages.我需要为男性和女性绘制一个图表,其中值以百分比表示。 I have seen the following question.我看到了以下问题。 Convert negative y axis to positive (matplotlib) 将负 y 轴转换为正 (matplotlib)

and it provides a solution to make the negative values positive which is what I need.它提供了一种使负值变为正值的解决方案,这正是我所需要的。 However, it will then show them in standard mode.但是,它将以标准模式显示它们。 0.01 instead of 1% 0.01 而不是 1%

I have played around with the order in the following commands, but can't seem to get it right.我已经使用了以下命令中的顺序,但似乎无法正确执行。

    ax.set_ylim(-0.01, 0.01)
    ax.set_yticklabels([str(abs(x)) for x in ax.get_yticks()])
    ax.yaxis.set_major_formatter(mtick.PercentFormatter(1))

I noticed that the yticklabels look like我注意到 yticklabels 看起来像

Text(-0.01, 0, '-1.00%')
Text(-0.0075, 0, '-0.75%')
Text(-0.005, 0, '-0.50%')
Text(-0.0025000000000000005, 0, '-0.25%')
Text(0.0, 0, '0.00%')
Text(0.0025000000000000005, 0, '0.25%')
Text(0.004999999999999999, 0, '0.50%')
Text(0.0075000000000000015, 0, '0.75%')
Text(0.01, 0, '1.00%')

Is there a way I can get rid of the - sign?有没有办法摆脱 - 符号?

PercentFormatter is not relevant when you manually change the content of yticklabels , so you have to do the job up to the end. PercentFormatter是不相关的,当你手动更改的内容yticklabels ,所以你必须做的工作到最后。 Here is an example with a sine curve, labelled from 100% to 0% to 100%:这是一个带有正弦曲线的示例,标记为 100% 到 0% 到 100%:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
ax.plot(x,y)
ax.set_yticklabels([f"{abs(100*x)}%" for x in ax.get_yticks()])
fig.show()

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

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