Plot画图
数据准备
import pymysql
from sqlalchemy import create_engine
import pandas as pd
import mysql.connector as sql
import time
def read_mysql(sql):
try:
engine = create_engine("mysql+pymysql://dw:dw@111.230.56.74:3306/dw?charset=utf8mb4")
table = pd.read_sql(sql,con=engine)
print ('数据库查询成功')
except :
print ('数据库查询失败')
return table
if __name__ == "__main__":
start_time = time.time() # 开始时间
sql = """
select date(日期),项目名称,max(等待分钟) as max_等待分钟,min(等待分钟) as min_等待分钟
,avg(等待分钟) as avg_等待分钟
from odl_disney_wait where date(日期)>="2018-10-01"
group by date(日期),项目名称
"""
try:
df = read_mysql(sql)
print(df.head())
except:
print('sql查询失败')
end_time = time.time() #结束时间
print("程序耗时%f秒." % (end_time - start_time))
数据库查询成功
date(日期) 项目名称 max_等待分钟 min_等待分钟 avg_等待分钟
0 2018-10-01 七个小矮人矿山车 75 5 48.3000
1 2018-10-01 与星球大战里的机器人朋友见面 0 0 0.0000
2 2018-10-01 创极速光轮-雪佛兰呈献 40 0 17.1071
3 2018-10-01 创界:雪佛兰数字挑战 0 0 0.0000
4 2018-10-01 加勒比海盗——沉落宝藏之战 15 0 9.7436
程序耗时29.226061秒.
基础配置
import matplotlib
import matplotlib as mpl
import matplotlib.pyplot as plt
import plotly.plotly
import plotly.tools as tls
import numpy as np
#设置用户名和API-Key
# plotly = {'Username':'kemimantou','API key':'GxDbixidr7OCQjJx3Lim'}
#plotly.tools.set_credentials_file(username='kemimantou', api_key='GxDbixidr7OCQjJx3Lim')
#plotly.offline.init_notebook_mode(connected=True)#离线使用
# 中文和负号的正常显示
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['figure.figsize'] = [10, 10] #设置figure_size尺寸
plotly.offline.init_notebook_mode(connected=True) # initiate notebook for offline plot
直方图
def plt_hist(df,var,step):
bins = np.arange(0, df[var].max(), step) # fixed bin size
plt.hist(df[var], # 绘图数据
bins = bins, # 指定直方图的条形数为20个
color = 'steelblue', # 指定填充色
edgecolor = 'k', # 指定直方图的边界色
label = '直方图' )# 为直方图呈现标签)
plt.title('%s直方图'%(var))
plt.xlabel('variable %s '%(var))
plt.ylabel('count计数')
#去除图形顶部边界和右边界的刻度
#plt.tick_params(top=False, right=False)
# 显示图例
#plt.legend()
# 显示图形
#plt.show()
fig = plt.gcf()
plotly_fig = tls.mpl_to_plotly(fig)
plotly.offline.iplot(plotly_fig, filename='mpl-basic-histogram')
if __name__ == "__main__":
plt_hist(df,'max_等待分钟',step=10)
条形图
条形图
条形图 和水平条形图的差异:plt.bar 和 plt.barh ,并且注意参数:width 和 heigth ;以及plt.xticks 和plt.yxticks
plt.rcParams['figure.figsize'] = [8,6]
bar_data = df.groupby(by=['项目名称'],as_index = False).agg({'max_等待分钟': 'max'});
bar_data = bar_data.sort_values(by=['max_等待分钟'], ascending=False)
bar_data = bar_data.head()
label_list = bar_data['项目名称'].tolist()
index_size = np.arange(bar_data['max_等待分钟'].size);
#竖向柱形图
plt_result = plt.bar(index_size, bar_data['max_等待分钟'], width=0.2, alpha=0.8,color='G' ,label="max_等待分钟")
plt.xticks([index + 0.2 for index in index_size], label_list)
plt.xlabel("项目名称")
plt.title("项目名称max_等待分钟")
plt.legend() # 设置题注
for result in plt_result:
height = result.get_height()
plt.text(result.get_x() + result.get_width() / 2, height+1, str(height), ha="center", va="bottom")
plt.show();
条形图示例2
### 条形图示例2:
#使用的是另外的一个数据集
# 设置中文字体和负号正常显示
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
data = {'年份':['2014', '2015', '2016', '2017'],
'num_list1':[20, 30, 15, 35],
'num_list2':[15, 30, 40, 20]}
plt_df = pd.DataFrame(data)
x = np.arange(plt_df['num_list1'].size)
"""
绘制条形图
left:长条形中点横坐标
height:长条形高度
width:长条形宽度,默认值0.8
label:为后面设置legend准备
"""
rects1 = plt.bar(x, height=plt_df['num_list1'], width=0.4, alpha=0.8, color='red', label="一部门")
rects2 = plt.bar([i + 0.4 for i in x], height=plt_df['num_list2'], width=0.4, color='green', label="二部门")
plt.ylim(0, 50) # y轴取值范围
plt.ylabel("数量")
"""
设置x轴刻度显示值
参数一:中点坐标
参数二:显示值
"""
plt.xticks([index + 0.2 for index in x], label_list)
plt.xlabel("年份")
plt.title("某某公司")
plt.legend() # 设置题注
# 编辑文本
for rect in rects1:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height+1, str(height), ha="center", va="bottom")
for rect in rects2:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height+1, str(height), ha="center", va="bottom")
plt.show()
水平条形图
plt.rcParams['figure.figsize'] = [17,10]
bar_data = df.groupby(by=['项目名称'],as_index = False).agg({'max_等待分钟': 'max'});
bar_data = bar_data.sort_values(by=['max_等待分钟'], ascending=True)
#bar_data = bar_data .head(6)
label_list = bar_data['项目名称'].tolist()
index_size = np.arange(bar_data['max_等待分钟'].size);
#水平柱形图
plt.barh(index_size, bar_data['max_等待分钟'], height=0.5, alpha=0.8,color='G',label="max_等待分钟");
plt.yticks([index + 0.2 for index in index_size], label_list)
## 标签
plt.xlim(0,250)
plt.xlabel("max_等待分钟")
plt.title("不同项目max_等待分钟")
for x, y in enumerate(bar_data['max_等待分钟']):
plt.text(y + 0.2, x - 0.1, '%s' %y)
plt.show()
plt.show();
# fig = plt.gcf()
# plotly_fig = tls.mpl_to_plotly(fig)
# plotly.offline.iplot(plotly_fig, filename='mpl-basic-bar')
#df.head()
#bar_data
#bar_data
# for x, y in enumerate(bar_data['max_等待分钟']):
# print(y + 0.2, x - 0.1, '%s' %y)
data = {'年份':['2014', '2015', '2016', '2017'],
'num_list1':[20, 30, 15, 35],
'num_list2 ':[15, 30, 40, 20]}
plt_df = pd.DataFrame(data)
|
年份 |
num_list1 |
num_list2 |
0 |
2014 |
20 |
15 |
1 |
2015 |
30 |
30 |
2 |
2016 |
15 |
40 |
3 |
2017 |
35 |
20 |