简体   繁体   中英

Line plot with two y-axes using matplotlib?

I have a list of (x,y) values like below.

k = [(3, 6), (4, 7), (5, 8), (6, 9), (7, 10), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)]

I would like create a plot that draws lines on opposite axes like below with the assumption that the axis values are in the range 1-15.

Please find the figure here

.

I tried using twinx and twiny, but not exactly sure how to achieve this. I think it might be easier to do using Microsoft Excel, but I have all my values in python npy files.

You can draw a collection of line segments using LineCollection. It is also possible to draw each line using plt.plot , but when there are lots of line segments, using LineCollection is more efficient:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.collections as mcoll

k = np.array([(3, 6), (4, 7), (5, 8), (6, 9), (7, 10), 
              (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)])
x = np.array([0,1])

fig, ax = plt.subplots()
points = np.stack([np.tile(x, (len(k),1)), k], axis=2)
line_segments = mcoll.LineCollection(points, linestyles='solid', colors='black', 
                                     linewidth=2)
ax.add_collection(line_segments)
ax.set_xticks([0, 1])
# Manually adding artists doesn't rescale the plot, so we need to autoscale (https://stackoverflow.com/q/19877666/190597)
ax.autoscale()
plt.show()

在此处输入图片说明

It could be simple :

import matplotlib.pyplot as plt
[plt.plot(d) for d in k]
plt.ylabel('some numbers')
plt.show()

gives me :

在此处输入图片说明

And with the labels :

import matplotlib.pyplot as plt
[plt.plot(d) for d in k]
plt.ylabel('some numbers')
ax = plt.gca()
ax.xaxis.set_ticks([0,1])
ax.xaxis.set_ticklabels(["BaseLine", "FollowUp"])
plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM