使用matplotlib在单个图上绘制三个数据集

0 投票
3 回答
11570 浏览
提问于 2025-04-18 18:41

我刚开始学习Python,所以如果这个问题很简单,请多包涵。

我有一个输出文件,里面有5列数据,具体如下:

Depth Data#1 Data#2 Data#3 Standard_deviation

这些列里总共有500个值,如果这有什么影响的话。

我想做的就是把数据#1、数据#2和数据#3(放在x轴上)与深度(放在y轴上)进行绘图。我希望数据#1是蓝色的,而数据#2和数据#3各自是红色的。

我希望图的大小是(14,6)。

我不想在这里绘制包含标准差的那一列。如果这样更简单的话,我可以直接把那一列从输出中去掉。

提前谢谢任何帮助!

3 个回答

2

在使用matplotlib的时候,如果我不知道怎么做,我通常会先浏览一下图库,找一些看起来和我想做的事情相似的例子,然后修改那里的代码。

这个例子里有你想要的大部分内容:

在这里输入图片描述

http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html

"""
This shows an example of the "fivethirtyeight" styling, which
tries to replicate the styles from FiveThirtyEight.com.
"""


from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 10)

with plt.style.context('fivethirtyeight'):
    plt.plot(x, np.sin(x) + x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 0.5 * x + np.random.randn(50))
    plt.plot(x, np.sin(x) + 2 * x + np.random.randn(50))


plt.show()

不过,这个例子里有很多你不需要的额外内容,但你要注意的是,plt.plot(...)可以被多次调用,这样就可以画出多条线。

接下来就是应用这个;

from matplotlib import pyplot    

#Make some data
depth = range(500)
allData = zip(*[[x, 2*x, 3*x] for x in depth])

#Set out colours
colours = ["blue", "red", "red"]


for data, colour in zip(allData, colours):
    pyplot.plot(depth, data, color=colour)

pyplot.show()

在这里输入图片描述

2

因为这个问题只涉及到绘图,所以我假设你已经知道怎么从文件中读取数据。至于绘图,你需要以下内容:

import matplotlib.pyplot as plt

#Create a figure with a certain size
plt.figure(figsize = (14, 6))

#Plot x versus y
plt.plot(data1, depth, color = "blue")
plt.plot(data2, depth, color = "red")
plt.plot(data3, depth, color = "red")

#Save the figure
plt.savefig("figure.png", dpi = 300, bbox_inches = "tight")

#Show the figure
plt.show()

savefig中使用选项bbox_inches = "tight"可以去掉图像周围多余的白色边框。

1

这是关于matplotlib的基础知识:

import pylab as pl

data = pl.loadtxt("myfile.txt")

pl.figure(figsize=(14,6))
pl.plot(data[:,1], data[:,0], "b")
pl.plot(data[:,2], data[:,0], "r")
pl.plot(data[:,3], data[:,0], "r")

pl.show()

撰写回答