matplotlib绘制了太多的滴答声 [英] matplotlib plots too many ticks
问题描述
我有一个大代码,可以输出多个图像.有时,情节看起来像这样(请参见下面的MWE):
I have a large code which outputs several images. At times, a plot will look like this (see MWE below):
请注意,x轴上的刻度线几乎彼此重叠,这看起来很糟糕.
Notice how the ticks in the x axis are almost overlapping each other, which looks pretty bad.
我的问题是:为什么matplotlib无法实现这一点,而只是绘制较少的滴答声(通常不会出现问题)?我该如何强制matplotlib以 general 的方式绘制较少的刻度线(即:我不是只针对该特定情节应用 的解决方案,这只是一个示例)?
My question is: why doesn't matplotlib realize this and simply plots fewer ticks (as it usually does without issues)? How can I force matplotlib to draw fewer ticks in a general way (ie: I'm not after a solution that applies only for this particular plot, this is just an example)?
MWE(如果代码看起来不必要地复杂,那是因为它只是更大代码的一小部分)
MWE (if the code looks unnecessarily complicated, it's because it's a small portion of a much larger code)
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import random
def scatter_plot(x, y):
ax = plt.subplot(gs[0:2, 0:2])
plt.xlim(min(x), 0.00158)
plt.xlabel('$x$', fontsize=16)
plt.ylabel('$y$', fontsize=16)
ax.minorticks_on()
plt.scatter(x, y)
# Generate random data.
x = [random.random() / 100. for i in xrange(10000)]
y = [random.random() for i in xrange(10000)]
# Define size of output figure.
fig = plt.figure(figsize=(30, 25)) # create the top-level container
gs = gridspec.GridSpec(10, 12) # create a GridSpec object
# Create plot.
scatter_plot(x, y)
# Save plot to file.
fig.tight_layout()
plt.savefig('out.png', dpi=150)
推荐答案
首先 import numpy as np
然后调用 ax.xaxis.set_ticks(np.arange(xmin, xmax, stepsize)))
,其中 xmin
是最小刻度值, xmax
是最大刻度值,而 stepsize
是连续刻度之间的差滴答声.使用 stepsize =(xmax-xmin)/tick_count
可能是有意义的,其中 tick_count
是您想要的刻度数.
First import numpy as np
and then call ax.xaxis.set_ticks(np.arange(xmin, xmax, stepsize))
, where xmin
is the minimum tick value, xmax
is the maximum tick value, and stepsize
is the difference between consecutive ticks. It probably makes sense to use stepsize = (xmax - xmin) / tick_count
, where tick_count
is the number of ticks you want.
这篇关于matplotlib绘制了太多的滴答声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!