1

I'm trying to plot data from .txt file.

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

Frist problem, Figure's y startpoint is fixed at the smallest of the .txt file's data(Y)

I have tried set_ylim or ymin. but it doesn't work..

Second problem, x axis is putting 10 before 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)

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!

voiDnyx
  • 975
  • 1
  • 11
  • 24
jhyyk
  • 55
  • 3
  • 8

1 Answers1

1

You are treating your numbers as string when you read them from file so you get lexicographical ordering. Cast them to int and the order becomes correct.

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?

voiDnyx
  • 975
  • 1
  • 11
  • 24