python - How can I generate this plot?
问题描述
Is there a library that I can use to generate the plot below?
The closest I got was to generate 2 separate plots and then convert them to numpy array images and to then sum them together. But I would not have the legends in my solution.
import cv2
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10),'b')
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.yaxis.set_label_position("right")
ax.spines['bottom'].set_color('blue')
ax.spines['right'].set_color('blue')
ax.xaxis.label.set_color('blue')
ax.yaxis.label.set_color('blue')
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='blue')
ax.tick_params(right=True, left=False, top=False, labelleft=False, labelright=True)
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10),'r')
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.xaxis.set_label_position("top")
ax.spines['top'].set_color('red')
ax.spines['left'].set_color('red')
ax.xaxis.label.set_color('red')
ax.yaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')
ax.tick_params(axis='y', colors='red')
ax.tick_params(left=True, right=False, bottom=False, top=True, labeltop=True, labelbottom=False)
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
解决方案
You can use twinx()
and twiny()
for this purpose
fig = plt.figure()
ax1 = plt.subplot(111)
line1, = ax1.plot(range1, data1, 'r', label='data1-range1')
ax1.set_xlabel('range1')
ax1.set_ylabel('data1')
ax1.xaxis.label.set_color('red')
ax1.yaxis.label.set_color('red')
ax1.tick_params(axis='both', colors='red')
_temp = ax1.twinx()
ax2 = _temp.twiny()
ax2.set_xlabel('range2')
line2, = ax2.plot(range2, data2, 'b', label='data2-range2')
ax2.tick_params(axis='x', colors='blue')
ax2.xaxis.label.set_color('blue')
_temp.tick_params(axis='y', colors='blue')
_temp.set_ylabel('data2', rotation=-90, labelpad=10, color='blue')
ax2.spines['left'].set_color('red')
ax2.spines['top'].set_color('blue')
ax2.spines['bottom'].set_color('red')
ax2.spines['right'].set_color('blue')
plt.legend([line1, line2], ['range1-data', 'range2-data2'], loc='lower right')
Edit 1: Edited the code to include spines
and coloring other text, ticks, and labels as well.
Edit 2: Included the legends for both plots as well.
推荐阅读
- ios - 等效于 WKWebView 上 UIWebView 的 paginationMode
- java - 如何在 Spring Boot 中从 YAML 配置创建地图?
- android - Android视图没有创建:没有这样的方法错误
- javascript - Angular 我不使用 (load) 调用函数
- ruby-on-rails - 未定义的方法错误 - 单表继承 - 路由错误
- c# - 从本地系统帐户下运行的 Windows 服务获取当前用户目录
- mysql - 其他表中的 AVG 连接结果
- android - 为什么添加 ViewPager 后状态栏颜色停止变化?
- python - 有没有办法在 Python 中实现全局计算属性?
- javascript - Webpack,extract-loader 不加载加载背景 url