网站更新内容:请访问: https://bigdata.ministep.cn/

Plot画图matplotlib

基础配置

In [70]:
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
 
 

直方图

In [12]:
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
In [127]:
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

In [141]:
### 条形图示例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()
 
 

水平条形图

In [142]:
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')
 
 
posted @ 2021-04-04 20:30  ministep88  阅读(135)  评论(0编辑  收藏  举报
网站更新内容:请访问:https://bigdata.ministep.cn/