python - Matplotlib 图例垂直旋转

标签 python matplotlib

有人知道是否可以在 matplotlib 中旋转图例吗?我用下面的代码画了一个简单的图,并在绘图中编辑了图形以显示我想要的内容。

plt.plot([4,5,6], label = 'test')
ax = plt.gca()
ax.legend()
plt.show()

http://www.abraham.dreamhosters.com/Capture.PNG

最佳答案

我遇到了一个类似的问题,并通过编写函数 legendAsLatex 来解决它,该函数生成一个 latex 代码以用作 y 轴的标签。该函数收集颜色、标记、线条样式和提供给绘图函数的标签。它需要启用 latex 并加载所需的包。以下是使用两个垂直轴的额外曲线生成绘图的代码。

from matplotlib import pyplot as plt
import matplotlib.colors as cor

plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{amsmath} \usepackage{wasysym}'+
    r'\usepackage[dvipsnames]{xcolor} \usepackage{MnSymbol}  \usepackage{txfonts}')

def legendAsLatex(axes, rotation=90) :
    '''Generate a latex code to be used instead of the legend. 
       Uses the label, color, marker and linestyle provided to the pyplot.plot.
       The marker and the linestyle must be defined using the one or two character
           abreviations shown in the help of pyplot.plot.
       Rotation of the markers must be multiple of 90.
    '''
    latexLine = {'-':'\\textbf{\Large ---}',
        '-.':'\\textbf{\Large --\:\!$\\boldsymbol{\cdot}$\:\!--}',
        '--':'\\textbf{\Large --\,--}',':':'\\textbf{\Large -\:\!-}'}
    latexSymbol = {'o':'medbullet', 'd':'diamond', 's':'filledmedsquare',
        'D':'Diamondblack', '*':'bigstar', '+':'boldsymbol{\plus}',
        'x':'boldsymbol{\\times}', 'p':'pentagon', 'h':'hexagon',
        ',':'boldsymbol{\cdot}', '_':'boldsymbol{\minus}','<':'LHD',
        '>':'RHD','v':'blacktriangledown', '^':'blacktriangle'} 
    rot90=['^','<','v','>']
    di = [0,-1,2,1][rotation%360//90]
    latexSymbol.update({rot90[i]:latexSymbol[rot90[(i+di)%4]] for i in range(4)})
    return ', '.join(['\\textcolor[rgb]{'\
            + ','.join([str(x) for x in cor.to_rgb(handle.get_color())]) +'}{'
            + '$\\'+latexSymbol.get(handle.get_marker(),';')+'$'
            + latexLine.get(handle.get_linestyle(),'') + '} ' + label 
                for handle,label in zip(*axes.get_legend_handles_labels())])

ax = plt.axes()
ax.plot(range(0,10), 'b-', label = 'Blue line')
ax.plot(range(10,0,-1), 'sm', label = 'Magenta squares')
ax.set_ylabel(legendAsLatex(ax))

ax2 = plt.twinx()
ax2.plot([x**0.5 for x in range(0,10)],  'ro', label = 'Red circles')
ax2.plot([x**0.5 for x in range(10,0,-1)],'g--', label = 'Green dashed line')
ax2.set_ylabel(legendAsLatex(ax2)) 

plt.savefig('legend.eps')

plt.close()

代码生成的图:

enter image description here

关于python - Matplotlib 图例垂直旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32012120/

相关文章:

python - 使用pyplot的线性回归中的奇怪图形

python - Matplotlib 中的垂直偏移刻度标签

python - 将 int64 转换为日期时间,格式为 %H :%M'

python - 根据其他列值处理缺失值

python - **(双星/星号)和 *(星号/星号)对参数有何作用?

python - 从字典中的自定义函数访问值

python - 使用 python 从没有表单标签但有文本输入的网站中抓取数据

python - matplotlib/pandas条形图的简单定制(标签、刻度等)

python - 显示 scipy 树状图的聚类标签

Python Pandas 绘制标题名称传递字符串