繁体   English   中英

我如何使用 matplotlib 从 .txt 文件中绘制数据

[英]how can i plot data from .txt file using matplotlib

我正在尝试从 .txt 文件中绘制数据。

这是我的 .txt 文件(test.txt)

0  81       
1  78       
2  76
3  74
4  81
5  79
6  80
7  81
8  83
9  83
10  83
11  82
  .
  .
22  81
23  80

我看过类似的问题

如何使用 matplotlib 从 .txt 文件中绘制数据? )但我有两个问题。

第一个问题,图的 y 起点固定在 .txt 文件数据(Y)中的最小值

我试过set_ylim 或 ymin 但它不起作用..

第二个问题,x 轴将 10 放在 2 之前。

我参考了很多数据,但结果并不好。

我想让它像下图

这是我的 py 代码和我的实际图形(.png 文件)

import matplotlib.pyplot as plt

with open('test.txt') as f:
    lines = f.readlines()

x = [line.split()[0] for line in lines]
y = [line.split()[1] for line in lines]

fig = plt.figure(figsize=(15,10))
ax1 = fig.add_subplot(111)
ax1.set_title("SMP graph")
ax1.set_xlabel('hour')
ax1.set_ylabel('smp')
ax1.bar(x,y, width=0.7)

fig1=plt.gcf()
plt.show()
plt.draw()
fig1.savefig('test.png')

先感谢您!

当您从文件中读取数字时,您将数字视为string ,以便获得字典顺序。 将它们转换为int并且顺序变得正确。

import matplotlib.pyplot as plt

with open('test.txt') as f:
    lines = f.readlines()
    x = [int(line.split()[0]) for line in lines]
    y = [int(line.split()[1]) for line in lines]

fig = plt.figure(figsize=(15,10))
ax1 = fig.add_subplot(111)
ax1.set_title("SMP graph")
ax1.set_xlabel('hour')
ax1.set_ylabel('smp')
ax1.bar(x,y, width=0.7)

fig1=plt.gcf()
plt.show()
plt.draw()

你认为你可以从这里拿走吗?

暂无
暂无

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

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