Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting multiple line graphs in matplotlib

I'm using matplotlib to draw line graphs and whenever I try to draw the second line graph, the y-axis gets printed two times.

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5]
y1 = ['1000', '13k', '26k', '42k', '60k', '81k']
y2 = ['1000', '13k', '27k', '43k', '63k', '85k']

plt.plot(x, y1)
plt.plot(x, y2, '-.')

plt.xlabel("X-axis data")
plt.ylabel("Y-axis data")
plt.title('multiple plots')
plt.show()

This is the code I'm using, what am I doing wrong.

Output:

Output

like image 547
Siddesh Avatar asked Dec 07 '25 05:12

Siddesh


2 Answers

Change the two lines:

y1 = ['1000', '13k', '26k', '42k', '60k', '81k']
y2 = ['1000', '13k', '27k', '43k', '63k', '85k']

to

y1 = [1000, 13000, 26000, 42000, 60000, 81000]
y2 = [1000, 13000, 27000, 43000, 63000, 85000]

It consists of two change. First, plot does not plot a string. Second, you change 'k' to multiples of 1000.

Try the following:

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5]
y1 = [1000, 13000, 26000, 42000, 60000, 81000]
y2 = [1000, 13000, 27000, 43000, 63000, 85000]

plt.plot(x, y1, label ='y1')
plt.plot(x, y2, '-.', label ='y2')

plt.xlabel("X-axis data")
plt.ylabel("Y-axis data")
plt.legend()
plt.title('multiple plots')
plt.show()

enter image description here

This also adds labels to the lines.

like image 173
Ka-Wa Yip Avatar answered Dec 08 '25 19:12

Ka-Wa Yip


Your y values are strings instead of numbers, matplotlib lets you plot them but there is no "number" scale to the plot so it simply add the new labels (strings like '85k') on top. A simple fix would be to replace the 'k' in all the strings with 'e3' and then cast all the values to a number using float().

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5]

y1 = ['1000', '13k', '26k', '42k', '60k', '81k']
y2 = ['1000', '13k', '27k', '43k', '63k', '85k']

Now convert and plot:

plt.plot(x, [float(i.replace('k', 'e3')) for i in y1])
plt.plot(x, [float(i.replace('k', 'e3')) for i in y2], '-.')

plt.xlabel("X-axis data")
plt.ylabel("Y-axis data")
plt.title('multiple plots')
plt.show()

Here I converted the strings just for the purpose of plotting.

like image 43
SiP Avatar answered Dec 08 '25 19:12

SiP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!