简体   繁体   English

使用matplotlib用两个y轴绘制线图?

[英]Line plot with two y-axes using matplotlib?

I have a list of (x,y) values like below. 我有一个(x,y)值的列表,如下所示。

k = [(3, 6), (4, 7), (5, 8), (6, 9), (7, 10), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)] 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. 我想创建一个在轴相反的轴上绘制线的图,如下所示,并假设轴值在1-15范围内。

Please find the figure here 请在这里找到图

.

I tried using twinx and twiny, but not exactly sure how to achieve this. 我尝试使用twinx和twiny,但不确定如何实现这一目标。 I think it might be easier to do using Microsoft Excel, but I have all my values in python npy files. 我认为使用Microsoft Excel可能更容易,但是我的所有值都存储在python npy文件中。

You can draw a collection of line segments using LineCollection. 您可以使用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: 也可以使用plt.plot绘制每条线,但是当有很多线段时,使用LineCollection效率更高:

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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