matplotlib图例中的线条样式没有正确显示

时间:2014-06-05 18:50:30

标签: matplotlib legend

所以我有七行的情节,我已经有效地使用线条和灰度来区分。

但是,根据图例条目的长度(我假设),某些线条样式无法正确显示。例如,在这张图片中:

this

CO2线应该与OH线具有相同的线型,但缺少最后一个小线段。

此外,HO2 linestyle看起来很奇怪,为什么个别行会像那样扩展?

我发现改变线条样式的唯一方法是更改​​图例项目的字体大小(因此我假设这是由于图例条目的长度)。我希望传说中的文字大小要小一些,但这会让线条更加糟糕。

有什么建议吗?

编辑:我确实找到了重现(某些)不良行为的方法。运行以下内容(尽可能简短)脚本:

import matplotlib.pyplot as plt
import pylab
import numpy as np
import math
import matplotlib as mpl

#defines a class that can spit out nice greyscale color styles
class BlackColorStyles:
    def __init__(self, numseries, linestyles = ['-', '--', '-.', ':'], AlphaMin = 0, AlphaMax = 0.6):
        self.linestyles = linestyles[:]
        #create color map
        count = 0
        self.numcolors = round(numseries / float(len(self.linestyles)) + 0.5)
        self.colormap = []
        for i in range(int(self.numcolors)):
            if (self.numcolors == 1):
                alpha = (AlphaMax, AlphaMax, AlphaMax)
            else:
                alpha = (AlphaMax - AlphaMin) * (i / float(self.numcolors - 1)) + AlphaMin
                alpha = (alpha, alpha, alpha)
            for style in self.linestyles:
                self.colormap.append(alpha)
    def getStyle(self, index):
        return (self.linestyles[index % len(self.linestyles)], self.colormap[index])

#change font
mpl.rc('font', **{'sans-serif' : 'Arial', 'family' : 'sans-serif'})

#size settings
fig_width_pt = 345.0 # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inch
golden_mean = (math.sqrt(5)-1.0)/2.0         # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt  # width in inches
fig_height = fig_width*golden_mean      # height in inches
fig_size =  [fig_width,fig_height]
#font sizes, etc.
params = {'backend': 'ps',
          'axes.labelsize': 10,
          'text.fontsize': 10,
          'legend.fontsize': 8,
          'xtick.labelsize': 8,
          'ytick.labelsize': 8,
          'text.usetex': True,
          'figure.figsize': fig_size,
          'figure.dpi': 1000,
          'savefig.dpi': 1000}
pylab.rcParams.update(params)

#legend labels
labels = ["T (K)", "co", "co2", "ho2", "nc7h16", "o2", "oh"]

#color styles
colormap = BlackColorStyles(len(labels))

#make simple lines on plot
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
twinaxis = ax.twinx()

#time series
time = np.linspace(0, 0.025, 1000)

#line thickness
thickness = 2
lines = []
#plot data
numlines = 7
for i in range (numlines):
    (format, mycolor) = colormap.getStyle(i)
    arr = np.zeros_like(time)
    arr.fill(i + 1)
    if (i == 0):
        lines += twinaxis.plot(time, arr, format, color = mycolor, linewidth = thickness, label = labels[i])
    else:
        lines += ax.plot(time, arr, format, color = mycolor, linewidth = thickness, label = labels[i])

#labels
ax.set_xlabel("time (s)")
twinaxis.set_ylabel("Temperature (K)")

n_legend_col = 3
#legend
labels = [l.get_label() for l in lines]
legend = plt.legend(lines, labels, loc='upper center', bbox_to_anchor = (0.5, 1.05), ncol = n_legend_col, fancybox = True)
legend.set_zorder(20)
legend.draggable(state=True)
#tight_layout and show
plt.tight_layout()
plt.show()

在windows7 x64,python 2.7.5上,通过Anaconda 1.9.1,生成this

请注意红色方框条目中没有第二个破折号!

0 个答案:

没有答案