简体   繁体   English

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

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

I'm trying to plot data from .txt file.我正在尝试从 .txt 文件中绘制数据。

here is my .txt file (test.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

I have looked at similar question我看过类似的问题

( How can you plot data from a .txt file using matplotlib? ) but I have two problems. 如何使用 matplotlib 从 .txt 文件中绘制数据? )但我有两个问题。

Frist problem, Figure's y startpoint is fixed at the smallest of the .txt file's data(Y)第一个问题,图的 y 起点固定在 .txt 文件数据(Y)中的最小值

I have tried set_ylim or ymin .我试过set_ylim 或 ymin but it doesn't work..但它不起作用..

Second problem, x axis is putting 10 before 2.第二个问题,x 轴将 10 放在 2 之前。

I refer to a lot of data, but the result was not good.我参考了很多数据,但结果并不好。

I want to make it like the following graph我想让它像下图

this is my py code and my actual graph (.png file)这是我的 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')

Thank you in advance!先感谢您!

You are treating your numbers as string when you read them from file so you get lexicographical ordering.当您从文件中读取数字时,您将数字视为string ,以便获得字典顺序。 Cast them to int and the order becomes correct.将它们转换为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()

Think you can take it from here?你认为你可以从这里拿走吗?

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

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