简体   繁体   中英

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)

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%

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

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. Here is an example with a sine curve, labelled from 100% to 0% to 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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