如何从python中的sqldf制作直方图

时间:2016-08-11 20:53:27

标签: python plot histogram sqldf

我在iPython notebook中编写了以下SQL查询

q = """SELECT * 
FROM Northeast ORDER BY counted desc LIMIT 10"""
display(sqldf(q))

df = pysqldf(q)

plt.bar(df)
plt.show()

我试图制作一个直方图,但我一直都会遇到错误需要高等等。我尝试以不同的方式获得不同的错误。是否有可能从sgldf得到一个条形直方图的结果,城市为x ax,种群为y ax?

1 个答案:

答案 0 :(得分:1)

以下脚本应该有助于您尝试执行的操作:

import pandas as pd
from pysqldf import SQLDF
import matplotlib.pyplot as plt


##Set up the sqldf function to query from the globals() variables
sqldf = SQLDF(globals())
##Since you're using ipython notebooks, put plots in line with this: %matplotlib inline

##Get some data from Wikipedia: Gets all sorts of information on cities in the Northeast
cities = pd.read_html('https://en.wikipedia.org/wiki/Northeastern_United_States',header = 0)
Northeast = cities[1] ##This where the top 10 cities are
Northeast.head(2) ## Take a look
Northeast.columns = ['Rank', 'MetropolitanArea', 'States', 'Population'] ##Change the columns to look better

##Run your query: This gets city name and Population
df = sqldf.execute('SELECT MetropolitanArea, Population FROM Northeast ORDER BY Population desc LIMIT 10;')

##This get the bar plot
df.plot(x='MetropolitanArea',y='Population',kind='bar')
plt.show()

谢谢!