python - 在 matplotlib 中仅向图例的一个组件添加背景颜色
问题描述
我知道如何在其中绘制matplotlib
图例,并且知道如何添加图例,例如本例中的我们:
我想修改图例并仅为图例的一个特定行(或组件)显示背景颜色。以图片为例,我希望红色虚线显示在黄色背景上(我知道这不是最佳选择,我只是将颜色用于说明目的)。
我知道如何为整个图例框添加背景,例如:
x = arange(0.,10,0.1)
a = cos(x)
b = sin(x)
c = exp(x/10)
d = exp(-x/10)
la = plt.plot(x,a,'b-',label='cosine')
lb = plt.plot(x,b,'r--',label='sine')
lc = plt.plot(x,c,'gx',label='exp(+x)')
ld = plt.plot(x,d,'y-', linewidth = 5,label='exp(-x)')
# Add the background to the legend
lege = plt.legend(loc="upper left", prop={'size':8})
lege.get_frame().set_facecolor('#FFFF00')
但是,如果我希望背景只突出显示一个特定的行/组件怎么办?
解决方案
这样做的方法是操纵图例的句柄。如果我将以下代码添加到您的示例中,我可以让它工作:
import matplotlib.patches as mpatches
sp = plt.gca()
# Call get_legend_handles_labels()
# this returns both the handles (the lines on the left side of the legend)
# And the labels: the text in the legend
handles, labels = sp.get_legend_handles_labels()
# Let's create a yellow rectangle
yellow_patch = mpatches.Patch(color='yellow')
# Replace the second handle (for the red line)
# With a tuple; this first draws the yellow patch and then the red line
handles[1] = (yellow_patch, handles[1])
plt.legend(handles, labels)
推荐阅读
- android - Android JNI - 谷歌控制台回溯崩溃不正确
- php - 如何在 preg_match() 中使用阿拉伯字母
- javascript - 通过cordova执行npm模块
- laravel - 限制在 whereHas 上返回哪些关系模型
- node.js - Nodejs,http post json
- go - 有没有办法确定使用 `flag.VisitAll` 时是否设置了标志?
- javascript - Ace 编辑器添加自定义 JS API
- foursquare - Foursquare 场地数据过时?
- xaml - 新的 OnPlatform/OnIdiom XAML 扩展 - 用于边距厚度
- android - 为什么内部 AsyncTask 需要是静态的,而 Thread 不需要?