【问题标题】:Scatter plot with point size and color based on dataframe column基于数据框列的点大小和颜色的散点图
【发布时间】:2021-10-11 05:14:47
【问题描述】:

我想在 seaborn/matplotlib 中制作散点图,其中点的大小由另一列中的值确定(在这种情况下为 TVD(depth)。然后,点的颜色由另一列中的值分隔立柱(LOF 型) 这里的列是 ["Pc","ISIP","TVD","LOF Type"]。图表看起来像这样 Pc-ISIP

【问题讨论】:

  • 请张贴一份你的样本以及你到目前为止所做的尝试

标签: python-3.x matplotlib seaborn scatter-plot


【解决方案1】:

我猜您想要的颜色分离来自数据框中的分类列。我会解决它以遍历切片数据帧:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'x':[1,1,2,3,4],'y':[2,4,3,7,5],
                   'weight':[2,4,8,5,6],'catnum':[2,3,5,1,7],
                   'catc':['car','car','bike','bike','truck']})

# regular example without categorical:
fig1, ax1 = plt.subplots()
size = 5 * df['weight'].to_numpy()**2
ax1.scatter(df.x,df.y,c=df.catnum,s=size)
fig1.suptitle('numerical demo')
plt.show()

# function to iterate through your categorical column
def _getItr(data,key):
    kinds = sorted(data[key].unique())
    itr = {}
    for i in range(len(kinds)):
        itr[i]=data[data[key]==kinds[i]]
    return itr, kinds


cf, cats = _getItr(df,'catc')

fig2, ax2 = plt.subplots()
for c in cf:
    ax2.scatter(cf[c]['x'],cf[c]['y'],s=(5 * cf[c]['weight'].to_numpy()**2),label=cats[c])
    
legend2 = ax2.legend()
for h in legend2.legendHandles: h.set_sizes([30.0])   # otherwize markers in legend have different size
fig2.suptitle('colors and legend from categorical')
plt.show()

example fig2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 2019-11-27
    • 2017-08-02
    • 2021-02-26
    • 1970-01-01
    • 2013-06-26
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多