Python-分类气泡图 [英] Python - Categorical bubble plot

查看:38
本文介绍了Python-分类气泡图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个12x17的数据框,想要创建一个类似于以下内容的分类气泡图:

I have a 12x17 dataframe and want to create a categorical bubble plot looking like this one:

https://i.stack.imgur.com/IvD58.png (from Categorical bubble plot for mapping studies)

My dataframe looks basically like this:

#      A     B     C
# X   0.3   0.2   0.4
# Y   0.1   0.4   0.1

I can't use matplotlib.scatter because it does not take categorical input and creating fake values doesn't work either because it's not n*n. Or can I? I couldn't figure it out. I found seaborn.stripplot which takes one categorical input but the size of all bubbles is the same so I am stuck.

Any ideas how I could create such a plot in python? Thanks a lot.

解决方案

I think a scatter plot is perfectly suitable to create this kind of categorical bubble plot.

Create the dataframe:

import pandas as pd
df = pd.DataFrame([[.3,.2,.4],[.1,.4,.1]], columns=list("ABC"), index=list("XY"))

Option 1: unstack the DataFrame

dfu = df.unstack().reset_index()
dfu.columns = list("XYS")

This creates a table like

   X  Y    S
0  A  X  0.3
1  A  Y  0.1
2  B  X  0.2
3  B  Y  0.4
4  C  X  0.4
5  C  Y  0.1

which you can plot column-wise. Since the sizes of scatters are points one would need to multiply the S column with some large number, like 5000 to get large bubbles.

import matplotlib.pyplot as plt
dfu["S"] *= 5000
plt.scatter(x="X", y="Y", s="S", data=dfu)
plt.margins(.4)
plt.show()

Option 2: create grid

Using e.g. numpy, one may create a grid of the dataframe's columns and index such that one may then plot a scatter of the flattened grid. Again one would need to multiply the dataframe values by some large number.

import numpy as np
import matplotlib.pyplot as plt

x,y = np.meshgrid(df.columns, df.index)

df *= 5000
plt.scatter(x=x.flatten(), y=y.flatten(), s=df.values.flatten())
plt.margins(.4)
plt.show()

In both cases the result would look like

这篇关于Python-分类气泡图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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