python代码实现数据可视化

数据可视化

使用python代码实现对数据进行可视化
包含柱状图,折线图,堆积图,小提琴图,散点图等


代码

#!/usr/bin/env python
# coding: utf-8

# In[1]:


from IPython.display import clear_output 
get_ipython().system('pip install fast_ml ')
clear_output()


# In[2]:



import pandas as pd 
import seaborn as sns  
import plotly.express as px 
import matplotlib.pyplot as plt
import warnings 
warnings.filterwarnings("ignore")


# In[3]:


from fast_ml.outlier_treatment import OutlierTreatment 
from sklearn.feature_selection import VarianceThreshold 
from sklearn.preprocessing import LabelEncoder 
from sklearn.tree import DecisionTreeClassifier   
from sklearn.model_selection import train_test_split
from sklearn import tree


# ID:ID
# Warehouse block:仓库区块
# Mode of shipment:运输方式
# Customer care calls:客户服务电话
# Customer rating:客户评价
# Cost of the product:产品成本
# Prior purchases:先前购买
# Product importance:产品重要性
# Gender:性别
# Discount offered:提供的折扣
# Weight in gms:克重
# Reached on time:准时到达
# ![1639989747%281%29.png](attachment:1639989747%281%29.png)

# In[39]:


df = pd.read_csv(r"Train.csv")


# <h2 style='border:3px solid DodgerBlue;'><center>Data Overview</center></h2>

# In[5]:


df.head()


# <h2 style='border:3px solid DodgerBlue;'><center>Data types</center></h2>

# In[6]:


df.dtypes


# <h2 style='border:3px solid DodgerBlue;'><center>Information about data</center></h2>

# In[7]:


df.info()


# <h2 style='border:3px solid DodgerBlue;'><center>Checking null Values</center></h2>

# In[8]:


df.isna().sum()


# In[9]:


df.shape


# <h2 style='border:3px solid DodgerBlue;'><center>Ware_house block</center></h2>

# In[105]:


df['Warehouse_block'].value_counts()


# In[106]:


sns.countplot(x = 'Warehouse_block',data = df)
plt.show()


# 由上图可以看出,F区块数量远多于其余区块数量;
# 柱形图是一种对数据分布情况的图形表示,可以更直观的看到各个数值的数量分布

# In[10]:


object_columns = df.select_dtypes(include=['object'])


# In[11]:


object_columns = df.select_dtypes(include=['object'])
warehouse = object_columns["Warehouse_block"].value_counts().reset_index() 
warehouse.columns = ['warehouse',"values"] 
fig = px.pie(warehouse,names='warehouse',values='values',color_discrete_sequence=px.colors.sequential.matter_r) 
fig.show()


# 仓库一共分为五个区块,分别为A,B,C,D,F,由图表可直观看出,F区数量最多,其余区块数量相同;饼图是用圆形及圆内扇形的角度来表示数值大小的图形,它主要用于表示一个样本(或总体)中各组成部分的数据占全部数据的比例

# <h2 style='border:3px solid DodgerBlue;'><center>gender</center></h2>

# In[40]:


df['Gender'].value_counts()


# In[41]:


sns.countplot(x = 'Gender',data = df)
plt.show()


# 由上图看出该电子商务公司中用户的男女数量比较接近;

# In[12]:


gender = object_columns['Gender'].value_counts().reset_index() 
gender.columns = ["Gender","Counts"]  
gender.drop("Gender",axis=1,inplace=True)
gender["Gender"] = ["Male","Female"]
fig = px.pie(gender,names='Gender',values='Counts',color_discrete_sequence=px.colors.sequential.Electric) 
fig.update_traces(textinfo='percent+label')


# 由上图看出该电子商务公司用户男性占比略高于女性;

# <h2 style='border:3px solid DodgerBlue;'><center>Mode of shipment</center></h2>

# In[42]:


df['Mode_of_Shipment'].value_counts()


# In[43]:


sns.countplot(x = 'Mode_of_Shipment',data = df)
plt.show()


# 由上图可以看出该电子商务的运输方式中,选用轮船运输的次数远多于其他航空运输以及公路运输;

# In[13]:


transport = object_columns["Mode_of_Shipment"].value_counts().reset_index() 
transport.columns = ["Mode","Values"] 
fig = px.pie(transport,names='Mode',values='Values',color_discrete_sequence=px.colors.sequential.Magenta_r) 
fig.update_traces(textinfo='percent+label')


# 由上图可以看出该电子商务公司运输方式中,选用轮船运输的次数比其余两种运输方式加和后的次数还多;

# <h2 style='border:3px solid DodgerBlue;'><center>Product importance</center></h2>

# In[44]:


df['Product_importance'].value_counts()


# In[45]:


sns.countplot(x = 'Product_importance',data = df)
plt.show()


# 由上图可以看出,该电子商务公司所售卖出去的商品中,重要性低的数量略多与重要性中的,重要性高的售卖出去的数量较低;

# In[14]:


product = object_columns['Product_importance'].value_counts().reset_index() 
product.columns = ['Importance','Values'] 
fig = px.pie(product,names='Importance',values='Values',color_discrete_sequence=px.colors.sequential.Emrld_r) 
fig.update_traces(textinfo='percent+label')


# 由上图可以看出,售卖出去的商品中,产品重要性为低以及中的数量远多于重要性高的;

# In[15]:


integer_columns = df.select_dtypes(include=['int64'])


# In[16]:


integer_columns


# <h2 style='border:3px solid DodgerBlue;'><center>Customer_care calls</center></h2>

# In[17]:


customer = df["Customer_care_calls"].value_counts().reset_index() 
customer.columns = ["Number of times","Value"] 
fig = px.pie(customer,names="Number of times",values="Value") 
fig.update_traces(textinfo='percent+label')


# 由上图可以看出,所售卖出去的商品中,单个货品的客服电话数量为7个,最少为2个,其中所有货品中,客服电话为4个的占比最大,为32.3%,客服电话为2个的占比最低,为2.24%;

# <h2 style='border:3px solid DodgerBlue;'><center>Customer ratings</center></h2>

# In[18]:


customer = df["Customer_rating"].value_counts().reset_index() 
customer.columns = ["Ratings","Value"]  


# In[19]:


customer["Ratings"] = ["Rating_"+str(i) for i in customer["Ratings"].tolist()]


# In[20]:


fig = px.pie(customer,names="Ratings",values="Value",color_discrete_sequence=px.colors.sequential.algae_r) 
fig.update_traces(textinfo='percent+label')


# 图中Rating为客户评价,Rating_1为最低,Rating_5为最高,看饼图可以看出,客户对商品的评价处于一个平均的状态,均大概有20%左右人;

# <h2 style='border:3px solid DodgerBlue;'><center>Prior_Purchases</center></h2>

# In[21]:


Prior_purchases = df["Prior_purchases"].value_counts().reset_index() 
Prior_purchases.columns = ["Prior_purchases","Value"] 
Prior_purchases = Prior_purchases[["Prior_purchases","Value"]]


# In[22]:


text1 = ["Experienced "+str(i)+" times before ordering" for i in Prior_purchases["Prior_purchases"].values.tolist()]


# In[23]:


Prior_purchases["Prior_purchases"] = text1
fig = px.pie(Prior_purchases,names="Prior_purchases",values="Value",color_discrete_sequence=px.colors.sequential.Darkmint_r) 
fig.update_traces(textinfo='percent+label')


# 图中表示的是用户在先前购买商品的数量,其中在之前购买过3次的人占比最高为36%,在之前购买6次以上的人占比最少,占比低于2%,由此可见,需要加强对老用户的维护

# <h2 style='border:3px solid DodgerBlue;'><center>Reached On time delivery</center></h2>

# In[24]:


Reached = df["Reached.on.Time_Y.N"].value_counts().reset_index() 
Reached.columns = ["Reached","Value"]  
Reached.drop("Reached",axis=1,inplace=True) 
Reached["Reached"] = ["successfully Reached","Not Successfully Reached"]
fig = px.pie(Reached,names="Reached",values="Value",color_discrete_sequence=px.colors.sequential.Darkmint_r) 
fig.update_traces(textinfo='percent+label')


# 上图代表的是货品准时到达以及延迟到达的占比,可以看出准时到达的占比为59.7%,未准时到达的占比为40.3%,需要对未准时到达的原因进行分析,提高到达准确率;

# <h2 style='border:3px solid DodgerBlue;'><center>Cost of the product</center></h2>

# In[27]:


sns.displot(data=df,x="Cost_of_the_Product",height=8,aspect=3,kde=True)


# 图中直方图表示的是产品成本的价格,由此可以看出产品成本多处于150到250间;直方图又称质量分布图,它是表示资料变化情况的一种主要工具。用直方图可以解析出资料的规则性,比较直观地看出产品质量特性的分布状态,对于资料分布状况一目了然,便于判断其总体质量分布情况

# In[28]:


df.columns


# In[29]:


sns.displot(data=df,x="Discount_offered",height=8,aspect=3,kde=True)


# 图中表示的是商品提供的折扣,由图看出,产品提供的折扣在0-10的数量最多;直方图又称质量分布图,它是表示资料变化情况的一种主要工具。用直方图可以解析出资料的规则性,比较直观地看出产品质量特性的分布状态,对于资料分布状况一目了然,便于判断其总体质量分布情况

# In[53]:


ots = OutlierTreatment() 
ots.fit(df,["Discount_offered"])  
df = ots.transform(df)


# In[54]:


plt.figure(figsize=(20,8))
df.boxplot(column="Discount_offered")


# 图中表示的是提供折扣的箱线图,折扣的中位数大概在6.8左右;箱线图(boxplot)属于到描述性统计(descriptive statistics), 描述性统计的作用简单的来说就是用数值来描述数据有何相同的地方又有何不同的地方,就是对数据做总结归纳. 而箱线图是一种使用五个数值(下边缘,第一分位数,中位数,第三分位数,上边缘)来描述数据集分布的方法, 就是观察数据集大概是集中再什么区域, 分布的情况是否是对称的还是说向左或向右偏, 有没有一些数据偏离的很离谱等等.
# 

# In[47]:


# making a lineplot to check the relation between customer care calls, customer ratings and gender

plt.figure(figsize = (18, 9))
sns.lineplot(x = 'Customer_care_calls', y = 'Customer_rating', hue = 'Gender', data = df,
             palette = 'rocket', ci = 0)
plt.title('Relation between Customer Care Calls and Customer Rating of Males and Females\n',
          fontsize = 15)
plt.show()


# 图中表示的是男性与女性用户在,客服电话数量对产品评价程度的影响关系,由图中可以看出,当客服数量为6个时,客户评价也最高;折线统计图不仅可以表示数量的多少,而且可以反映同一事物在不同时间里的发展变化的情况

# In[27]:


mode = df.groupby(["Mode_of_Shipment"])["Warehouse_block"].value_counts().to_frame()


# In[28]:


mode.columns = ["Count"] 
df1 = mode.reset_index(level=[0,1]) 
df1.head()


# <h2 style='border:3px solid DodgerBlue;'><center>Mode of shipment belongs to Various ware_house blocks</center></h2>

# In[29]:


px.sunburst(df1,path=["Mode_of_Shipment","Warehouse_block"],values="Count",color_discrete_sequence=px.colors.sequential.Greys_r)


# 图形表示的是各运输渠道下,仓库区块的分布,从图中可以看出无论实在轮船运输还是航空运输或公路运输下F区块的数量都是最多的,所以可适当增加F仓块的数量;旭日图中每个级别的数据通过1个圆环表示,离原点越近代表圆环级别越高,最内层的圆表示层次结构的顶级,然后一层一层去看数据的占比情况。越往外,级别越低,且分类越细。因此,它既能像饼图一样表现局部和整体的占比,又能像矩形树图一样表现层级关系。

# <h2 style='border:3px solid DodgerBlue;'><center>Mode_of_shipment related to their product_importance</center></h2>

# In[30]:


importance = df.groupby(["Mode_of_Shipment"])["Product_importance"].value_counts().to_frame() 
importance.columns = ["Count"] 
importance = importance.reset_index(level=[0,1]) 


# In[31]:


px.sunburst(importance,path=["Mode_of_Shipment","Product_importance"],values="Count",color_discrete_sequence=px.colors.sequential.GnBu_r)


# 图形表示的是各运输渠道下,各货品重要性的分布情况,从图中可以看出无论实在轮船运输还是航空运输或公路运输下,商品重要性为高的数量都是最小的,且低于重要性低的以及中等的,所以可适当增加F仓块的数量;旭日图中每个级别的数据通过1个圆环表示,离原点越近代表圆环级别越高,最内层的圆表示层次结构的顶级,然后一层一层去看数据的占比情况。越往外,级别越低,且分类越细。因此,它既能像饼图一样表现局部和整体的占比,又能像矩形树图一样表现层级关系。

# <h2 style='border:3px solid DodgerBlue;'><center>which type of shipment can carry more weight</center></h2>

# In[35]:


Product_importance = df.groupby(["Product_importance"])["Reached.on.Time_Y.N"].value_counts().to_frame() 
Product_importance.columns = ["Count"] 
Product_importance = Product_importance.reset_index(level=[0,1]) 
Product_importance["Reached.on.Time_Y.N"] = ["Reached","Not Reached","Reached","Not Reached","Reached","Not Reached"] 
px.sunburst(Product_importance,path=["Product_importance","Reached.on.Time_Y.N"],values="Count")


# 图中表示的是货品不同重要性下,货品是否准时到达,由图中可以看出,就算在不同重要性下,也没有对货品是否准时到达产生很大的影响;旭日图中每个级别的数据通过1个圆环表示,离原点越近代表圆环级别越高,最内层的圆表示层次结构的顶级,然后一层一层去看数据的占比情况。越往外,级别越低,且分类越细。因此,它既能像饼图一样表现局部和整体的占比,又能像矩形树图一样表现层级关系。

# <h2 style='border:3px solid DodgerBlue;'><center>How many items are delivered on time based on product_importance</center></h2>

# In[32]:


load = df.groupby(["Mode_of_Shipment"])["Weight_in_gms"].sum().reset_index() 
px.bar(load,x="Mode_of_Shipment",y="Weight_in_gms",color_discrete_sequence=px.colors.sequential.ice)


# 图中表示的是各运输方式所承载的货物的重量,其中轮船运输所承载的货物重量远高于航空运输以及公路运输;柱形图 图形显示的比较清晰、直观,并能同时对比各个项目在某特定时间内的差异

# <h2 style='border:3px solid DodgerBlue;'><center>At what range of product_weight reaches delivery on time?</center></h2>

# In[45]:


plt.figure(figsize=(20,8))
sns.histplot(data=df,x="Weight_in_gms",hue="Reached.on.Time_Y.N",element='poly')


# 图中表示的是货物的重量对货品准时到达的影响,由图中可以看出货品越重,货品未准时到的可能性也越大;直方图又称质量分布图,它是表示资料变化情况的一种主要工具。用直方图可以解析出资料的规则性,比较直观地看出产品质量特性的分布状态,对于资料分布状况一目了然,便于判断其总体质量分布情况

# <h2 style='border:3px solid DodgerBlue;'><center>Whether rating depends upon the cost_of_the_product</center></h2>

# In[47]:


plt.figure(figsize=(20,8))
sns.catplot(data=df,x="Customer_rating",y="Cost_of_the_Product",color="darkblue",kind="swarm")


# 由图中看出,客户的评价与产品成本之间没有什么关系;用两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式。散点图将序列显示为一组点。值由点在图表中的位置表示。类别由图表中的不同标记表示。散点图通常用于比较跨类别的聚合数据

# In[55]:


#创建散点图,看看产品成本和折扣之间的关系,以及看产品是否能按时到达

plt.figure(figsize = (15, 7))
sns.scatterplot(x='Discount_offered', y='Cost_of_the_Product', data=df, hue='Reached.on.Time_Y.N')

plt.show()


# 图中表示的是产品折扣与产品成本间的关系是否影响货物准时到达;由图中可以看出产品的折扣约大,产品准时到达的数量越大;用两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式。散点图将序列显示为一组点。值由点在图表中的位置表示。类别由图表中的不同标记表示。散点图通常用于比较跨类别的聚合数据
# 

# In[57]:


#2000 - 4000 and 6000+ gram products are not delivered on time every time.
#Delivered on time products' weights changing between 1000-2000 and 4000-6000 grams.
fig, ax = plt.subplots(figsize=(9, 5))
sns.scatterplot(x="Weight_in_gms",y="Cost_of_the_Product",hue="Reached.on.Time_Y.N",data=df,edgecolor=colors_dark[0],palette="deep")
ax.legend(["Not delivered on time","Delivered on time"],loc='upper center', bbox_to_anchor=(0.5, -0.2), ncol=2, borderpad=1, frameon=True, fontsize=10)
plt.ylabel("Cost_of_the_Product",fontsize=12, fontweight='light', color=colors_dark[0])
plt.xlabel("Weight_in_gms",fontsize=12, fontweight='light', color=colors_dark[0])
plt.title("Weight_in_gms - Cost_of_the_Product", fontsize=18, fontweight='bold', color=colors_dark[0])
plt.show()


# In[51]:


figure = plt.figure(figsize=(15,8))
sns.scatterplot(x="Cost_of_the_Product",y="Discount_offered",hue="Reached.on.Time_Y.N",style="Customer_rating",
               data=df)
plt.show()


# In[48]:


fig = px.histogram(data_frame = df,x = 'Warehouse_block',color='Reached.on.Time_Y.N',title = "<b>Warehouse vs Reached on Time or not</b>")
fig.update_layout(bargap=0.2)
fig.show()


# 从图中可以看出大约60%货物准时到达;反映数据细分和总体情况,我们常常会使用到堆积条形图,这种图形让我们既能看到整体推移情况,又能看到某个分组单元的总体情况,还能看到组内组成部分的细分情况,一举多得

# In[49]:


fig = px.histogram(data_frame = df,x = 'Mode_of_Shipment',color='Reached.on.Time_Y.N',title = "<b>mode of shipment vs Reached on Time or not</b>")
fig.update_layout(bargap=0.2)
fig.show()


# 无论采用何种装运方式,几乎60%的货物都能按时到达

# In[60]:


import matplotlib.pyplot as plt
import math
import numpy as np
import pandas as pd
# from plotnine.themes.seaborn_rcmod import mpl
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm,colors


# In[52]:


pd.set_option('display.max_rows', 500)

pd.set_option('display.max_columns', 500)

pd.set_option('display.width', 1000)
x = df.drop(['Warehouse_block','Mode_of_Shipment','Product_importance','Gender'],axis = 1)
for i in x.columns:
    sns.violinplot(x = i, data = x,color = 'yellowgreen')   
    plt.xlabel(i)
    plt.show()


# 小提琴图 小提琴图类似于箱线图,不同之处在于它们还显示了数据在不同值下的概率密度。这些图包括数据中位数的标记和指示四分位距的框,如标准箱线图所示。叠加在此箱线图上的是核密度估计。与箱线图一样,小提琴图用于表示不同“类别”之间的变量分布(或样本分布)的比较。

# In[52]:


plt.figure(figsize=(20,8)) 
sns.heatmap(df.corr(),annot=True,vmin=-1,vmax=1,center=0,linewidths=3,linecolor='darkgreen')


# 由图中可以看出各个变量间的相关性关系;热力图可以更加直观的比较出各个变量间的相关性关系,可以看数据表里多个特征两两的相似度

网盘分享的文件:数据可视化.html
链接:https://pan.baidu.com/s/1BOTi4iwprfngd6sZjfEPYw
提取码:832V

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山林里的迷路人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值