Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python plot two lists with different length

I have two lists with different prices. The first list is for the years 2008-2018 and the second for the years 2010-2018. How I can plot them under the condition that the years 2008 to 2018 are on the X-axis and the second list starts in 2010?

I have the following as an example of a short code:

from matplotlib import pyplot as plt

Geb_b30 = [11, 10, 12, 14, 16, 19, 17, 14, 18, 17]
Geb_a30 = [12, 10, 13, 14, 12, 13, 18, 16]

fig, ax = plt.subplots()
ax.plot(Geb_b30, label='Prices 2008-2018', color='blue')
ax.plot(Geb_a30, label='Prices 2010-2018', color = 'red')
legend = ax.legend(loc='center right', fontsize='x-large')
plt.xlabel('years')
plt.ylabel('prices')
plt.title('Comparison of the different prices')
plt.show()
like image 887
Pyrmon55 Avatar asked Aug 07 '18 12:08

Pyrmon55


People also ask

Can we plot two lists in Python?

Also note that you can only plot one chart per call. For multiple, overlapping charts you'll need to call plt. bar repeatedly.

How do you avoid overlapping plots in python?

Dot Size. You can try to decrease marker size in your plot. This way they won't overlap and the patterns will be clearer.


2 Answers

I suggest you to simply define the x values (i.e. the list of years) for each set of points, and to pass them in parameters of ax.plot(), as follows:

from matplotlib import pyplot as plt

Geb_b30 = [11, 10, 12, 14, 16, 19, 17, 14, 18, 17]
years_b30 = range(2008,2018)
Geb_a30 = [12, 10, 13, 14, 12, 13, 18, 16]
years_a30 = range(2010,2018)

fig, ax = plt.subplots()
ax.plot(years_b30, Geb_b30, label='Prices 2008-2018', color='blue')
ax.plot(years_a30, Geb_a30, label='Prices 2010-2018', color = 'red')
legend = ax.legend(loc='center right', fontsize='x-large')
plt.xlabel('years')
plt.ylabel('prices')
plt.title('Comparison of the different prices')
plt.show()
like image 95
Laurent H. Avatar answered Nov 02 '22 23:11

Laurent H.


IIUC, just pad your missing years with None/NaN:

import pandas as pd

years = list(range(2008, 2018))
Geb_b30 = [11, 10, 12, 14, 16, 19, 17, 14, 18, 17]
Geb_a30 = [None, None, 12, 10, 13, 14, 12, 13, 18, 16]
df = pd.DataFrame({"years":years, "b30": Geb_b30, "a30": Geb_a30})

df.plot(x="years")

plot

like image 39
andrew_reece Avatar answered Nov 03 '22 00:11

andrew_reece