使用pandas和seaborn绘图

在这里插入图片描述

1.线形图

在pandas中,Series和DataFrame都有一个用于生成各类图表的plot()方法,默认生成的是线型图。

链接:pandas.Series.plotpandas.DataFrame.plot的官方文档。

为指定的Series生成折线图:

data = pandas.Series(numpy.random.randn(7).cumsum(0))

print(data)
data.plot(style="k.-.", rot=30, grid=True)
0    1.390847
1    0.547206
2    0.520530
3   -0.398884
4   -0.486248
5   -1.123840
6   -0.196571
dtype: float64

在这里插入图片描述


为指定的DataFrame生成折线图:

data = pandas.DataFrame(numpy.random.randn(7, 3).cumsum(0), columns=["A", "B", "C"])

print(data)
data.plot(style=["o-", "x:", "^--"], title="A - B - C", figsize=(16, 9))
          A         B         C
0 -2.275296 -0.337922 -1.526811
1 -0.999222 -1.224919 -2.670045
2 -1.407898 -0.593406 -3.933100
3 -0.088125 -0.486278 -3.090612
4 -0.220403  0.643248 -5.308337
5 -0.819526  1.557874 -5.718351
6 -1.358460  2.450793 -5.874556

在这里插入图片描述


2.柱状图

plot.bar()plot.barh()分别用于绘制垂直和水平的柱状图,此时Series和DataFrame的索引将会被用作刻度。

为指定Series生成柱状图:

fig, axes = matplotlib.pyplot.subplots(1, 2) # 创建一个1行2列的Figure对象

data = pandas.Series(numpy.random.rand(7), index=list('ABCDEFG'))
data.plot.bar(ax=axes[0], rot=0)
data.plot.barh(ax=axes[1])
A    0.317882
B    0.178443
C    0.490655
D    0.653693
E    0.880824
F    0.923257
G    0.787972
dtype: float64

在这里插入图片描述


为指定DataFrame生成柱状图:

data = pandas.DataFrame(numpy.random.rand(6, 4),
                  index=["1", "2", "3", "4", "5", "6"],
                  columns=pandas.Index(['A', 'B', 'C', 'D']))

print(data)
data.plot.bar(rot=0)
          A         B         C         D
1  0.079122  0.184886  0.141924  0.311727
2  0.490384  0.710730  0.712868  0.328058
3  0.340345  0.907243  0.593340  0.796208
4  0.369004  0.501489  0.062952  0.967165
5  0.562360  0.296670  0.432107  0.458429
6  0.011503  0.150241  0.810124  0.269063

在这里插入图片描述


为指定DataFrame生成堆积柱状图:

data = pandas.DataFrame(numpy.random.rand(6, 4),
                  index=["1", "2", "3", "4", "5", "6"],
                  columns=pandas.Index(['A', 'B', 'C', 'D']))

print(data)
data.plot.bar(stacked=True)
          A         B         C         D
1  0.847808  0.955484  0.652715  0.707678
2  0.213419  0.343561  0.301768  0.536410
3  0.643131  0.208405  0.097245  0.833812
4  0.632353  0.612214  0.340517  0.909366
5  0.446358  0.934332  0.771776  0.690315
6  0.046287  0.760079  0.621550  0.596409

在这里插入图片描述


3.直方图和密度图

在seaborn中使用displot()函数绘制直方图,使用kdeplot()函数绘制核密度图。

为指定Series生成直方图:

left = numpy.random.normal(0, 1, size=1000) # 均值为5 方差为10 共1000个点
right = numpy.random.normal(10, 2, size=1000) # 均值为10 方差为5 共1000个点

values = pandas.Series(numpy.concatenate([left, right])) # 将两个正态分布整合

seaborn.displot(values, bins=30)

在这里插入图片描述


为指定Series生成密度图:

left = numpy.random.normal(0, 1, size=1000) # 均值为5 方差为10 共1000个点
right = numpy.random.normal(10, 2, size=1000) # 均值为10 方差为5 共1000个点

values = pandas.Series(numpy.concatenate([left, right])) # 将两个正态分布整合

seaborn.kdeplot(values)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43686863/article/details/124802663