python - 独立处理图例标记
问题描述
我有两种线的情节:实线和虚线。实线和虚线都代表不同条件下的相同数量,并且它们具有相同的颜色。
现在,我想添加一个ax.text()
实线的标记来表示实线表示该条件下的数量,另一个ax.text()
带有虚线的标记表示另一个条件。不知何故,我的意思是这样的:
ax.text(0.9, 0.5, solid_marker + 'condition 1')
ax.text(0.9, 0.4, dashed_marker + 'condition 2')
好吧,就像这张照片中的东西:
我想做的例子:
有人知道怎么做吗?是否可以在图中的随机文本中使用标记的符号?
谢谢!
解决方案
您的图例规格不是标准的。您需要手动创建它。这是一个可运行的代码,可以产生你需要的东西。
#import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
# Need to create legends manually
# First legend
#red_patch = mpatches.Patch(color='red', label='The red data')
black_line = mlines.Line2D([], [], color='black', linewidth=1.5, label=r'$Z_n$')
green_line = mlines.Line2D([], [], color='green', linewidth=1.5, label=r'$Z_p$')
red_line = mlines.Line2D([], [], color='red', linewidth=1.5, label=r'$Z_\pi$')
# Second legend
line_solid = mlines.Line2D([], [], color='black', linestyle='-', linewidth=1.5, label=r'$n_\beta = n_o$')
line_dashed = mlines.Line2D([], [], color='black', linestyle='--', linewidth=1.5, label=r'$n_\beta = n_o/2$')
first_legend = plt.legend(handles=[black_line, green_line, red_line], loc=1)
ax = plt.gca().add_artist(first_legend)
second_legend = plt.legend(handles=[line_solid, line_dashed], loc='best', \
bbox_to_anchor=(0.5, 0.20, 0.5, 0.5)) #best upper-right
second_legend.set_frame_on(False)
plt.show()
输出图:
推荐阅读
- javascript - 如何使用 Flask AJAX 将 python 正确连接到 javascript
- python - 如何使用结构模式匹配检测可散列类型?
- javascript - 可以将 Shiny 管理器与 js 代码结合使用吗?
- react-native - 全局检查器,如果用户令牌存在于 Redux Saga 的每个屏幕上
- recursion - Clojure:递归函数中的 NullPointerException
- image - 在 Next.js 中导入本地图像时遇到问题
- google-cloud-functions - 对 GCP Cloud Function 内存使用有何影响
- jenkins - 启用 AzureAD 时,如何使用 JCasC 插件为 jenkins 管理员帐户创建 api 令牌?
- python-3.x - Python cv2:视频不播放
- python - BeautifulSoup:AttributeError:“NoneType”对象没有属性“文本”