文章目录

  • 前言
  • 一、柱状图
  • 二、线型图
  • 三、词云图
  • 四、散点图

前言

在数据分析的过程中,常常需要对各种数据进行EDA(Exploratory Data Analysis)的工作。而在其中,画图是最为直观的,也是数据分析师经常需要完成的工作,因此,能够画的一手好图,是评价一个数据分析师是否称职的标准之一。本文会不定期更新各种绘图代码以及其对应的结果,当有需要的时候,方便大家查阅。
代码来源如下:

  1. Exploration of data step by step

一、柱状图

fig, ax = plt.subplots(figsize = (16, 6))
plt.subplot(1, 2, 1)
plt.title('Distribution of pets age');
train['Age'].plot('hist', label='train');
test['Age'].plot('hist', label='test');
plt.legend();plt.subplot(1, 2, 2)
plt.title('Distribution of pets age (log)');
np.log1p(train['Age']).plot('hist', label='train');
np.log1p(test['Age']).plot('hist', label='test');
plt.legend();

plt.figure(figsize=(10, 6));
sns.violinplot(x="AdoptionSpeed", y="Age", hue="Type", data=train);
plt.title('AdoptionSpeed by Type and age');


下面这个柱状图比较有意思,以下图的例子来看。正常有5个type,从type0到type4。以type2为例,我们可以算出type2在所有5个type中的占比,记为Ratio(type2,all)。而从数据当中,又已知整体数据可以分成两个类,如图片中红色和灰色图框所示。这两类可以是“狗”vs“猫”,“大人”vs“小孩”,“国内”vs“国外”等等。那么我们可以进一步分别计算Ratio(type2,‘dog’)和Ratio(type2,‘cat’)。接下来,可以计算(Ratio(type2,‘dog’)-Ratio(type2,‘all’))/Ratio(type2,‘all’), 就可以知道当将‘猫’和‘狗’分开讨论时,在type2这一类比是比平均水平高还是低,高多少或者低多少。

main_count = train['AdoptionSpeed'].value_counts(normalize=True).sort_index()
def prepare_plot_dict(df, col, main_count):"""Preparing dictionary with data for plotting.I want to show how much higher/lower are the rates of Adoption speed for the current column comparing to base values (as described higher),At first I calculate base rates, then for each category in the column I calculate rates of Adoption speed and find difference with the base rates."""main_count = dict(main_count)plot_dict = {}for i in df[col].unique():val_count = dict(df.loc[df[col] == i, 'AdoptionSpeed'].value_counts().sort_index())for k, v in main_count.items():if k in val_count:plot_dict[val_count[k]] = ((val_count[k] / sum(val_count.values())) / main_count[k]) * 100 - 100else:plot_dict[0] = 0return plot_dictdef make_count_plot(df, x, hue='AdoptionSpeed', title='', main_count=main_count):"""Plotting countplot with correct annotations."""g = sns.countplot(x=x, data=df, hue=hue);plt.title(f'AdoptionSpeed {title}');ax = g.axesplot_dict = prepare_plot_dict(df, x, main_count)for p in ax.patches:h = p.get_height() if str(p.get_height()) != 'nan' else 0text = f"{plot_dict[h]:.0f}%" if plot_dict[h] < 0 else f"+{plot_dict[h]:.0f}%"ax.annotate(text, (p.get_x() + p.get_width() / 2., h),ha='center', va='center', fontsize=11, color='green' if plot_dict[h] > 0 else 'red', rotation=0, xytext=(0, 10),textcoords='offset points')  plt.figure(figsize=(18, 8));
make_count_plot(df=all_data.loc[all_data['dataset_type'] == 'train'], x='Type', title='by pet Type')

def plot_four_graphs(col='', main_title='', dataset_title=''):"""Plotting four graphs:- adoption speed by variable;- counts of categories in the variable in train and test;- adoption speed by variable for dogs;- adoption speed by variable for cats;    """plt.figure(figsize=(20, 12));plt.subplot(2, 2, 1)make_count_plot(df=train, x=col, title=f'and {main_title}')plt.subplot(2, 2, 2)sns.countplot(x='dataset_type', data=all_data, hue=col);plt.title(dataset_title);plt.subplot(2, 2, 3)make_count_plot(df=train.loc[train['Type'] == 1], x=col, title=f'and {main_title} for dogs')plt.subplot(2, 2, 4)make_count_plot(df=train.loc[train['Type'] == 2], x=col, title=f'and {main_title} for cats')plot_four_graphs(col='Pure_breed', main_title='having pure breed', dataset_title='Number of pets by pure/not-pure breed in train and test data')

sns.factorplot('Type', col='Gender', data=all_data, kind='count', hue='dataset_type');
plt.subplots_adjust(top=0.8)
plt.suptitle('Count of cats and dogs in train and test set by gender');

接下来,是比较正常的柱状图

#Now lets do the same for all the variables with a simple for loop:#get a the column names into a list
feature_variables = train_df.columns.values.tolist()#for each of the feature variables, doesn't include Id and Pawpularity by using [1:-1]
#show a boxplot and distribution plot against pawpularity
for variable in feature_variables[1:-1]:fig, ax = plt.subplots(1,2)sns.boxplot(data=train_df, x=variable, y='Pawpularity', ax=ax[0])sns.histplot(train_df, x="Pawpularity", hue=variable, kde=True, ax=ax[1])plt.suptitle(variable, fontsize=20, fontweight='bold')fig.show()

二、线型图

data = []
for a in range(5):df = train.loc[train['AdoptionSpeed'] == a]data.append(go.Scatter(x = df['Age'].value_counts().sort_index().index,y = df['Age'].value_counts().sort_index().values,name = str(a)))layout = go.Layout(dict(title = "AdoptionSpeed trends by Age",xaxis = dict(title = 'Age (months)'),yaxis = dict(title = 'Counts'),))
py.iplot(dict(data=data, layout=layout), filename='basic-line')

三、词云图

fig, ax = plt.subplots(figsize = (16, 12))
plt.subplot(1, 2, 1)
text_cat = ' '.join(all_data.loc[all_data['Type'] == 'Cat', 'Name'].fillna('').values)
wordcloud = WordCloud(max_font_size=None, background_color='white',width=1200, height=1000).generate(text_cat)
plt.imshow(wordcloud)
plt.title('Top cat names')
plt.axis("off")plt.subplot(1, 2, 2)
text_dog = ' '.join(all_data.loc[all_data['Type'] == 'Dog', 'Name'].fillna('').values)
wordcloud = WordCloud(max_font_size=None, background_color='white',width=1200, height=1000).generate(text_dog)
plt.imshow(wordcloud)
plt.title('Top dog names')
plt.axis("off")plt.show()

四、散点图

plt.figure(figsize=(16, 10));
sns.scatterplot(x="Fee", y="Quantity", hue="Type",data=all_data);
plt.title('Quantity of pets and Fee');

数据EDA绘图常用代码相关推荐

  1. 科研数据统计绘图常用软件介绍【持续更新】

    科研数据处理的内容 常用软件 当前流行的图形可视化和数据分析软件有Matlab,Mathmatica和Maple等.这些软件功能强大,可满足科技工作中的许多需要,但使用这些软件需要一定的计算机编程知识 ...

  2. mysql四列数据表代码_MySQL数据库常用代码

    MySQL数据库常用代码启动数据库服务:[ net Start MySQL ] 使用命令登录:[ Mysql -h localhost -u root -p] 关闭数据库服务: [net stop m ...

  3. python代码示例图形-纯干货:手把手教你用Python做数据可视化(附代码)

    原标题:纯干货:手把手教你用Python做数据可视化(附代码) 导读:制作提供信息的可视化(有时称为绘图)是数据分析中的最重要任务之一.可视化可能是探索过程的一部分,例如,帮助识别异常值或所需的数据转 ...

  4. python画图代码大全-纯干货:手把手教你用Python做数据可视化(附代码)

    原标题:纯干货:手把手教你用Python做数据可视化(附代码) 导读:制作提供信息的可视化(有时称为绘图)是数据分析中的最重要任务之一.可视化可能是探索过程的一部分,例如,帮助识别异常值或所需的数据转 ...

  5. python读取nc数据并绘图

    使用python读取nc数据并绘图 获取nc数据的相关信息 绘图 用matplotlib绘图 用Basemap绘图 用Cartopy绘图 安装Cartopy包 获取nc数据的相关信息 from net ...

  6. Python画图常用代码总结,这20个画图代码现拿现用

    目录 前言 1.散点图 2.带边界的气泡图 3.带线性回归最佳拟合线的散点图 4.抖动图 5.计数图 6.边缘直方图 7.边缘箱形图 9.矩阵图 10.发散型条形图 11.发散型文本 12.发散型包点 ...

  7. Visdom常用代码

    Visdom常用代码 文章目录 Visdom常用代码 vis.line vis.bar vis.histogram 自定义图 // 安装 pip install visdom //启动 python ...

  8. pytorch常用代码

    20211228 https://mp.weixin.qq.com/s/4breleAhCh6_9tvMK3WDaw 常用代码段 本文代码基于 PyTorch 1.x 版本,需要用到以下包: impo ...

  9. GitHub上7000+ Star的Python常用代码合集

    作者 | 二胖并不胖 来源 | 大数据前沿(ID:bigdataqianyan) 今天二胖给大家介绍一个由一个国外小哥用好几年时间维护的Python代码合集.简单来说就是,这个程序员小哥在几年前开始保 ...

最新文章

  1. python 元组传参 *args 字典传参 **kwargs 的用法
  2. java cglib jar包_Java面试题|反射必看的4道面试题
  3. python培训班时间 费用-广州python培训班收费标准
  4. Unity3D 游戏引擎之IOS高级界面发送消息与Unity3D消息的接收(九)
  5. java 启动程序设置classpath/加载jar、类的方式
  6. 关闭linux终端,查看、关闭登录到linux的终端
  7. KMP算法 java版本
  8. angular 构建可以动态挂载的配置服务
  9. 无心剑中译雪莱诗14首
  10. 如何去掉自动弹出IE9介绍页
  11. 远程登录工具 —— filezilla(FTP vs. SFTP)、xshell、secureCRT
  12. 如何生成JDK帮助文档
  13. 计算机内存满了 可是硬盘空的,为什么计算机内存不足
  14. HTML5 中 40 个最重要的技术点
  15. 《中国人工智能系列白皮书——智能驾驶》精编
  16. face_recognition IndexError: list index out of range
  17. rt-thread物联网开发板mqtt实验
  18. mui下拉刷新 ,无法滑动
  19. 【无敌浪子】python爬取足球赛事数据
  20. IoT设备与手机App之间如何实现实时消息通信——业务场景最佳实践

热门文章

  1. 无眠的滴滴,不再高傲
  2. 使用FireBreath写浏览器插件(二)
  3. 第37届ACM全球总决赛入围高校名单
  4. 转载:天涯——散文天下——《小驴坑爹记》——作者:南方孤驴
  5. 数论 毕达哥斯拉三元组 + 欧拉函数 + 容斥原理 hdu3939
  6. PKI/CA与数字证书技术大全
  7. android 仿多米音乐点击弹出歌词界面(部分)
  8. MQC手游行业解决方案详解
  9. 城市交通导航最短路径查询
  10. Pytorch实现LSTM对股票进行多步预测