首页 > 解决方案 > How can I generate this plot?

问题描述

Is there a library that I can use to generate the plot below?

enter image description here

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,))

enter image description here

enter image description here

标签: pythonmatplotlibseaborn

解决方案


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')

Re-edited picture

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.


推荐阅读