一个简单的美化
目录
一、问题描述二、解决方案三、完整代码一、问题描述
例如,我的x轴显示的刻度太密集(图1),想让显示数据看起来更为稀疏(图2)
二、解决方案
增加一行代码↓应该不难看懂,三个参数分别最小最大显示范围,刻度显示间距。使用后仅显示规定的范围和刻度间距
plt.xticks(np.arange(0, 31, step=5))
三、完整代码
from matplotlib import pyplotimport matplotlib.pyplot as pltfrom matplotlib.font_manager import FontPropertiesfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15)import matplotlibimport numpy as npfrom mpl_toolkits.axes_grid1.inset_locator import inset_axesfrom mpl_toolkits.axes_grid1.inset_locator import mark_insetfrom matplotlib.patches import ConnectionPatch%matplotlib inlineplt.rcParams['figure.figsize'] = (8.0, 6.0) # set default size of plotsplt.rcParams['image.interpolation'] = 'nearest'plt.rcParams['image.cmap'] = 'gray'plt.rcParams['font.sans-serif']=['SimHei']plt.rcParams['axes.unicode_minus']=False# 设置标题大小plt.rcParams['font.size'] = '16'#解决画多幅图时出现图形部分重叠fig = plt.figure()matplotlib.rcParams.update({'text.usetex': False,'font.family': 'stixgeneral','mathtext.fontset': 'stix',})myfont = FontProperties(fname='/home/linuxidc/.local/share/fonts/文泉驿正黑.ttf')#准备数据x = range(0,31,2)A=[0.2204262385828951,0.30839304560351055,0.4176158354528364,0.5689115113547377,0.7132088021728286,0.8170438670019559,0.874248496993988,0.8998229892687244,0.9022254048694502,0.9059819476369345,0.909439441977,0.9087585175336547,0.9070491438736936,0.906199789461,0.909012423535,0.905820399113082]B=[0.16086354829781346,0.24623673832139087,0.37067344907663385,0.5243875153820338,0.6455296269608115,0.7488125174629785,0.8000445335114674,0.8252572187188848,0.8275862068965517,0.8340528115714526,0.837546918379,0.837903717245582,0.8390037802979764,0.8358911851072082,0.8319986653319986,0.8359756097560975]C=[0.18306116800442845,0.2870632672332389,0.4144089350879133,0.552415258978,0.710936757829,0.8372170997485331,0.9124159429971054,0.9341066489655936,0.946792993279718,0.9503133935078769,0.9521488062187674,0.952635311063099,0.9535668223259951,0.9552372984652889,0.9439895451006562,0.9501552106430155]#绘图fig, ax = plt.subplots(1, 1)ax.plot(x, A, marker='H',linewidth=2,markersize=7,label=u'A')ax.plot(x, B, marker='s',linewidth=2,markersize=7,label=u'B')ax.plot(x, C, marker='D',linewidth=2,markersize=7,label=u'C')plt.grid(linestyle='-.') plt.grid(True)y_major_locator=MultipleLocator(0.1)x_major_locator=MultipleLocator(2)ax=plt.gca()ax.xaxis.set_major_locator(x_major_locator)ax.yaxis.set_major_locator(y_major_locator)plt.ylim(0,1.0)plt.xlim(0,31)plt.legend() # 让图例生效plt.title('XXX')plt.xlabel('X-axis',fontproperties=font_set) #X轴标签plt.ylabel("Y-axis",fontproperties=font_set) #Y轴标签plt.xticks(np.arange(0, 31, step=5))plt.grid(linestyle='-.') plt.show()
如果觉得《解决python画图坐标轴数据太密集的问题(显示部分刻度值)》对你有帮助,请点赞、收藏,并留下你的观点哦!