《利用Python进行数据分析》书中例子都是用IPython作为开发环境,问我一直在用Pycharm,这导致了plot还不能显示绘图。出错的代码如下:
import json
import pandas as pd
from pandas import DataFrame,Series
path = r'C:\Users\long\Desktop\python\pydata-book-2nd-edition\datasets\bitly_usagov\example.txt'
records = [json.loads(line) for line in open(path)]
time_zones = [rec['tz'] for rec in records if 'tz' in rec]
frame = DataFrame(records)
clean_tz = frame['tz'].fillna('Missing')
clean_tz[clean_tz == ''] = 'Unknown'
tz_counts = clean_tz.value_counts()
tz_counts[:10].plot(kind='barh',rot=0)
解决方法:导入matplotlib.pyplot库,绘图后再调用matplotlib.pyplot.show()方法就能把绘制的图显示出来了。
修改后代码如下:
import json
import pandas as pd
from pandas import DataFrame,Series
import matplotlib.pyplot as plt
path = r'C:\Users\long\Desktop\python\pydata-book-2nd-edition\datasets\bitly_usagov\example.txt'
records = [json.loads(line) for line in open(path)]
time_zones = [rec['tz'] for rec in records if 'tz' in rec]
frame = DataFrame(records)
clean_tz = frame['tz'].fillna('Missing')
clean_tz[clean_tz == ''] = 'Unknown'
tz_counts = clean_tz.value_counts()
tz_counts[:10].plot(kind='barh',rot=0)
plt.show(tz_counts[:10].plot(kind='barh',rot=0))