matplotlib作图如何避免坐标轴显示过于密集

18,028 阅读1分钟

使用matplotlib作图时,当x轴为字符型的数据时matplotlib不能智能的处理,作图结果通常是一堆字符挤在一起什么都看不清,这时就需要自己手动调整x轴布局,这里有一个小技巧。

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
y = np.random.randn(79).cumsum()
x = Sales.index
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
plt.show()

只需要添加

ax.xaxis.set_major_locator(ticker.MultipleLocator(base=10))

ticker.MultipleLocator中的参数base是x轴显示的间隔:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
np.random.seed(1)
y = np.random.randn(79).cumsum()
x = Sales.index
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=10))
plt.show()