0

I am plotting a set of numbers against their position in a file.

For instance, the first few lines of the file are shown below:

93
90
77
79
83
96
111
115
115
118
129
138
153
147
151
164
166
162
161
157
165
148
161
161
143

Now, I want to plot each number against the line number in the file.

X axis - line number in the file
Y axis - the value of the number at that specific line

I wrote the following code which plots the graph for first 5000 numbers in the file:

import matplotlib.pyplot as plt
import sys

X, Y = [], []
counter = 1

for line in open(sys.argv[1], 'r'):
  X.append(float(counter))
  Y.append(float(line))
  counter = counter + 1
  if counter > 5000:
    break

plt.plot(X, Y)
plt.show()

The graph looks like shown below:

enter image description here

However, I want X-Axis to show more detailed intervals and the graph should look like below:

enter image description here

Neon Flash
  • 3,113
  • 12
  • 58
  • 96
  • Looks like a duplicate for https://stackoverflow.com/questions/12608788/changing-the-tick-frequency-on-x-or-y-axis-in-matplotlib – VirtualVDX Dec 28 '18 at 15:57
  • Possible duplicate of [Changing the "tick frequency" on x or y axis in matplotlib?](https://stackoverflow.com/questions/12608788/changing-the-tick-frequency-on-x-or-y-axis-in-matplotlib) –  Dec 28 '18 at 16:01
  • 1
    Both these duplicates are not relevant. The problem is solved here not by increasing the tick frequency but by using a bar plot with thin bar width as answered below – Sheldore Dec 28 '18 at 16:18

2 Answers2

1

Explanation

You have got it almost correct, all you need to do is change the type of graph to be used.

Code

plt.bar(X, Y, align='center', width=0.2)
plt.show()

Change the width according to the thickness of the bar you need.

Resources

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html

  • 1
    for this many points i would use a stem plot. additionally, using `bar` will attempt to label every single bar with its own tick. the result will not look good or even be legible. – Paul H Dec 28 '18 at 16:12
  • 1
    @PaulH: Not necessarily. On my system, I get only major ticks for the example provided at intervals of 5 (0, 5, 10, 15...). Stem plot has other parameters to take care of: markers, connecting lines, base line etc.. Bar plot is rather simple – Sheldore Dec 28 '18 at 16:22
0

Your problem is that your are using plot (which plots arrays as continuous line) while matplotlib has other functions such as matplotlib.pyplot.vlines which can make your requested image .

This function spares you from making the X list in your example (which speed up your program) if no line is empty in your file.

Otherwise you can put zero in Y list if the line is empty, here's the vlines docs

I think there's no need to rewrite your program,as it is straightforward now.

Yasin Yousif
  • 969
  • 7
  • 23