Matplotlib具有不同的x span和较小尺寸的标记

时间:2017-06-05 12:43:30

标签: python matplotlib plot

我创建了一个图,但是你可以看到x轴有重叠的条目,我希望不同的x轴标记之间的跨度很明显,可以看到数字1,5,10不同。

此外,绘制值的标记比较重。如何减小尺寸?

import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;

filename = 'plot.pdf';

fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2);
rc('lines',mew=2);
rc('text', usetex=True);

x = np.array([1,5,10,50,100,250,500]);

t_err = np.array([106.50, 99.53, 94.70, 94.65, 93.40, 93.38, 92.81]);
c_err  = np.array([ 66.48, 65.11, 62.08, 60.09, 59.36, 60.32, 61.17]);
lns1 = ax1.plot(x,t_err,'bs:', label="T");
lns2 = ax1.plot(x,c_err,'bs-',label="C");

ax1.set_ylabel('Error',color='b',size=12);
ax1.set_ylim([50,100]);
ax1.set_xlim([1,500]);
ax1.set_xticks(x);
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=10, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=10);

lns = lns1 + lns2;
labs = [l.get_label() for l in lns];

ax1.set_xlabel('# of Iterations',size=14);
ax1.legend(lns, labs, bbox_to_anchor=(1.02,1.0), loc=2, borderaxespad=2.5, ncol = 1);
fig.savefig(filename,format='pdf',transparent=True, bbox_inches='tight');

1 个答案:

答案 0 :(得分:1)

您可以手动绘制一件事并添加另一件作为标签。例如(我指出评论部分我已经改变了):

import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;

filename = 'plot.pdf';

fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2);
rc('lines',mew=2);
rc('text', usetex=False); # Change to False because I don't have Latex

x = np.array([1,5,10,50,100,250,500]);
xo = np.array([10,20,30,40,70,110,160]); # changed here

t_err = np.array([106.50, 99.53, 94.70, 94.65, 93.40, 93.38, 92.81]);
c_err  = np.array([ 66.48, 65.11, 62.08, 60.09, 59.36, 60.32, 61.17]);
lns1 = ax1.plot(xo ,t_err,'bs:', label="T"); # changed here
lns2 = ax1.plot(xo ,c_err,'bs-',label="C"); # changed here

ax1.set_ylabel('Error',color='b',size=12);
ax1.set_ylim([50,100]);
ax1.set_xlim([1,xo.max()]); #changed here
ax1.set_xticks(xo) # changed here
ax1.set_xticklabels([str(i) for i in x]); # Changed here
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=10, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=10);

lns = lns1 + lns2;
labs = [l.get_label() for l in lns];

ax1.set_xlabel('# of Iterations',size=14);
ax1.legend(lns, labs, bbox_to_anchor=(1.02,1.0), loc=2, borderaxespad=2.5, ncol = 1);
plt.show()

结果如下:

Manually deforming X axis in matplotlib

但显然这远远不是自动化的事情。您可以构建自己的"变形轴功能"使用这种方法制作一个情节,或者探索一下matplotlib transformations。我不知道如何使用后者,所以我不想发表评论(我甚至不确定它能否实现这种效果)。希望你能用更好的方法得到答案。同时希望这会有所帮助。