简体   繁体   English

在x轴上的刻度标签的Plotlot间距

[英]Pyplot spacing of tick labels on x axis

What is the correct approach to spacing out xticks in a pyplot chart? 在pyplot图表中间隔xticks的正确方法是什么? For example I am trying to plot logarithms in a Jupiter notebook. 例如,我试图在Jupiter笔记本中绘制对数。 I have a lot of data points on the y axis and this creates too many xticks (the labels overlap each other and are unreadable). 我在y轴上有很多数据点,这会产生太多的xticks(标签相互重叠并且不可读)。 How do I configure the plot to only print a label every 10 xticks? 如何将绘图配置为每10 xt打印一次标签?

I tried to use 我试着用

plt.xticks(np.arange(10))

but this just renders the first 10 labels in the same tightly grouped fashion. 但这只是以相同的紧密分组方式呈现前10个标签。

%matplotlib inline
import matplotlib.pyplot as plt
x = np.arange(0.1, 10, 0.1)
plt.plot(np.log(x), label='$\log_e$')
plt.plot(np.log2(x), label='$\log_2$')
plt.plot(np.log10(x), label='$\log_{10}$')
plt.xticks(np.arange(10))
plt.grid()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

糟糕的xticks

A part of your problem arises, because you have omitted the x coordinates in your plot functions. 出现问题的一部分,因为您在绘图函数中省略了x坐标。 If you were using 如果你正在使用

plt.plot(x, np.log(x))

you would not have the spacing problem. 你不会有间距问题。

If you omit the x coordinate it gets replaced internaly by a np.arange(len(y)) and so your xaxis has values from 0 to 100 instead of 0 to 10. 如果省略x坐标,则会被np.arange(len(y))替换为内部,因此xaxis的值为0到100而不是0到10。

For reference: 以供参考:

在此输入图像描述 在此输入图像描述

In general matplotlib has socalled locators to deal with tick spacings: 一般来说,matplotlib有所谓的定位器来处理滴答间距:
https://matplotlib.org/examples/ticks_and_spines/tick-locators.html https://matplotlib.org/examples/ticks_and_spines/tick-locators.html

One option is to use log axees eg change: 一种选择是使用日志轴,例如更改:

plt.xticks(np.arange(10))

to: 至:

plt.semilogx(np.arange(10))

And you will get: 你会得到: 在此输入图像描述

See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.semilogx.html?highlight=semilogx#matplotlib.pyplot.semilogx for more options. 有关更多选项,请参阅https://matplotlib.org/api/_as_gen/matplotlib.pyplot.semilogx.html?highlight=semilogx#matplotlib.pyplot.semilogx

One option is to give a list of values to the ticks: 一种选择是给刻度值提供一个值列表:

plt.xticks([0,10,30,100])

Will give: 会给: 在此输入图像描述

but there are other options such as specifying a step to the arange function. 但还有其他选项,例如指定arange函数的step

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

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