plt.xticks如何设置字符串为刻度

pyplot里的xticks默认刻度之间是相同距离,
假使我们想要显示:
 x轴刻度为[1997 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017]
 y轴刻度为[0, 1, 2, 3, 4, 5]
 在每个x刻度下的值为[1, 3, 1, 4, 5, 4, 4, 5, 4, 2, 3, 1, 1, 4, 4, 3]的图像。

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np

font = FontProperties(fname=r"C:\windows\fonts\simsun.ttc", size=13)
plt.xlabel(u'年份', fontproperties=font, fontdict={'family': 'Times New Roman',
                                                 'color': 'black',
                                                 'weight': 'normal',
                                                 'size': 13})
plt.ylabel(u'论文数', fontproperties=font, fontdict={'family': 'Times New Roman',
                                                  'fontstyle': 'italic',
                                                  'color': 'black',
                                                  'weight': 'normal',
                                                  'size': 13})

plt.xlim(1996, 2018)
x = np.arange(2003, 2018, 1)
x = np.insert(x, 0, 1997)
plt.xticks(x, fontsize=9)

plt.ylim(0, 5.5)
y = np.linspace(0, 5, 11)
plt.yticks(y, fontsize=9)

value = np.array([1, 3, 1, 4, 5, 4, 4, 5, 4, 2, 3, 1, 1, 4, 4, 3])
l1, = plt.plot(x, value, '--', color='b', linewidth=1.5, marker='^')

plt.show()

输出:

很明显,上图不是我们想要的结果,我们想要刻度均等的显示。
那么为了解决上面的问题,我们考虑将x坐标里的数字设为字符的形式来表示在图标上(代码如下):

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np

font = FontProperties(fname=r"C:\windows\fonts\simsun.ttc", size=13)
plt.xlabel(u'年份', fontproperties=font, fontdict={'family': 'Times New Roman',
                                                 'color': 'black',
                                                 'weight': 'normal',
                                                 'size': 13})
plt.ylabel(u'论文数', fontproperties=font, fontdict={'family': 'Times New Roman',
                                                  'fontstyle': 'italic',
                                                  'color': 'black',
                                                  'weight': 'normal',
                                                  'size': 13})

# 将x轴的刻度设为字符
year = np.arange(2003, 2018, 1)
year = list(year)
year.insert(0, np.int32(1997))
x = range(len(year))
plt.xticks(range(len(year)), year, fontsize=9, rotation=45)

plt.ylim(0, 5.5)
y = np.linspace(0, 5, 11)
plt.yticks(y, fontsize=9)

value = np.array([1, 3, 1, 4, 5, 4, 4, 5, 4, 2, 3, 1, 1, 4, 4, 3])
l1, = plt.plot(x, value, '--', color='b', linewidth=1.5, marker='^')

plt.show()

最终可得到我们想要的结果。

你可能感兴趣的:(plt.xticks如何设置字符串为刻度)