python绘制多个直方图 [英] python plot multiple histograms

查看:54
本文介绍了python绘制多个直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有30个变量的数据框X, v1,v2 ... v30 col_name=[v1,v2.....v30]

I have a dataframe X with 30 variables, v1, v2 ... v30 and col_name=[v1,v2.....v30]

对于每个变量,我想绘制直方图以了解变量分布.但是,编写代码来逐个绘制太手工了,我可以像for循环那样一次绘制30个直方图吗?

For each variable, I want to plot the histogram to understand the variable distribution. However, it is too manual to write code to plot one by one, can I have something like a for loop to draw 30 histograms one under another at one go?

例如:

for i in range(30):
  hist(np.array(X[col_name[i]]).astype(np.float),bins=100,color='blue',label=col_name[i],normed=1,alpha=0.5)

我该怎么做?就像一页图形一样(每个图形都有标题和标签),这样我就可以向下滚动以阅读.

How can I do that? Like one page of graphs (each with title and label) so that I can scroll down to read.

推荐答案

你可以这样做:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

np.random.normal(0, 10)

df = pd.DataFrame({
        'v1': np.random.normal(0, 3, 20),
        'v2': np.random.normal(0, 3, 20),
        'v3': np.random.normal(0, 3, 20),
        'v4': np.random.normal(0, 3, 20),
        'v5': np.random.normal(0, 3, 20),
        'v6': np.random.normal(0, 3, 20),        
    })


# Generically define how many plots along and across
ncols = 3
nrows = int(np.ceil(len(df.columns) / (1.0*ncols)))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(10, 10))

# Lazy counter so we can remove unwated axes
counter = 0
for i in range(nrows):
    for j in range(ncols):

        ax = axes[i][j]

        # Plot when we have data
        if counter < len(df.columns):

            ax.hist(df[df.columns[counter]], bins=10, color='blue', alpha=0.5, label='{}'.format(df.columns[counter]))
            ax.set_xlabel('x')
            ax.set_ylabel('PDF')
            ax.set_ylim([0, 5])
            leg = ax.legend(loc='upper left')
            leg.draw_frame(False)

        # Remove axis when we no longer have data
        else:
            ax.set_axis_off()

        counter += 1

plt.show()

结果:

改编自:如何在 matplotlib 中获取多个子图?

这篇关于python绘制多个直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆