Python matplotlib 轴上的不同精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43528317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Different precision on matplotlib axis
提问by MatMorPau22
My teacher said that in a graph I must label the axis like 0, 0.25, 0.5
not 0.00,0.25,0.50,...
.
I know how to label it like 0.00,0.25,0.50
(plt.yticks(np.arange(-1.5,1.5,.25))
), however, I don't know how to plot the ticklabels with different precision.
我的老师说在图表中我必须像0, 0.25, 0.5
not一样标记轴0.00,0.25,0.50,...
。我知道如何将其标记为0.00,0.25,0.50
( plt.yticks(np.arange(-1.5,1.5,.25))
),但是,我不知道如何以不同的精度绘制刻度标签。
I've tried to do it like
我试过这样做
plt.yticks(np.arange(-2,2,1))
plt.yticks(np.arange(-2.25,2.25,1))
plt.yticks(np.arange(-1.5,2.5,1))
without avail.
无济于事。
回答by johannesmik
This was already answered, for example here Matplotlib: Specify format of floats for tick lables. But you actually want to have another format than used in the referenced question.
这已经得到了回答,例如这里Matplotlib:Specify format of floats for tick labels。但您实际上想要使用另一种格式而不是引用问题中使用的格式。
So this code gives you your wished precision on the y axis
所以这段代码给你你想要的 y 轴精度
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
ax.yaxis.set_ticks(np.arange(-2, 2, 0.25))
x = np.arange(-1, 1, 0.1)
plt.plot(x, x**2)
plt.show()
You can define your wished precision in the String that you pass to FormatStrFormatter. In the above case it is "%g" which stands for the general format. This format removes insignificant trailing zeros. You could also pass other formats, like "%.1f" which would be a precision of one decimal place, whereas "%.3f" would be a precision of three decimal places. Those formats are explained in detail here.
您可以在传递给 FormatStrFormatter 的字符串中定义所需的精度。在上述情况下,“%g”代表一般格式。此格式删除无关紧要的尾随零。您还可以传递其他格式,例如“%.1f”,它的精度为小数点后一位,而“%.3f”的精度为小数点后三位。此处详细解释了这些格式。
回答by ImportanceOfBeingErnest
In order to set the ticks' positions at multiples of 0.25 you can use a matplotlib.ticker.MultipleLocator(0.25)
. You can then format the ticklabels using a FuncFormatter
with a function that strips the zeros from the right of the numbers.
为了将刻度的位置设置为 0.25 的倍数,您可以使用matplotlib.ticker.MultipleLocator(0.25)
. 然后,您可以使用FuncFormatter
带有从数字右侧去除零的函数来格式化刻度标签。
import matplotlib.pyplot as plt
import matplotlib.ticker
plt.plot([-1.5,0,1.5],[1,3,2])
ax=plt.gca()
f = lambda x,pos: str(x).rstrip('0').rstrip('.')
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(f))
plt.show()