Milano
Milano

Reputation: 18725

Create a line chart from dictionary - Matplotlib

Is it possible to create a line chart using dictionary? I've managed how to create pillar chart but I want line to be there instead of pillars.

Here is my code:

from datetime import datetime, timedelta
from db import get_min_prices_and_dates
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(plt.style.available[4])

date_from = (datetime.now()-timedelta(days=0)).date()
date_to = (datetime.now()+timedelta(days=+30)).date()
D = get_min_prices_and_dates(date_from,date_to,4,7,'AMS') # THIS IS A DICTIONARY - DATES:PRICES

plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), D.keys())

plt.show()

I want to have this type of plot:

enter image description here

Instead of: enter image description here

Upvotes: 2

Views: 19577

Answers (2)

Hun
Hun

Reputation: 3847

I don't think you can have a line plot straight out of dict. You have to extract keys and values and then make a line plot.

dates = list(D.keys())           # list() needed for python 3.x
prices = list(D.values())        # ditto
ax.plot_date(dates, prices, '-') # this will show date at the x-axis

Upvotes: 5

Joshua Mannheimer
Joshua Mannheimer

Reputation: 153

why not use plt.plot(x,y) for a standard line plot with x=range(len(D)) and y=D.values?

Upvotes: 0

Related Questions