如何根据数据框中的一系列值制作具有不同散点大小和颜色的散点图?

How to make a scatter plot with varying scatter size and color corresponding to a range of values from a dataframe?

我有一个数据框

df = 
Magnitude,Lon,Lat,Depth
3.5  33.3   76.2    22
3.5  33.1   75.9    34
2.5  30.5   79.6    25
5.5  30.4   79.5    40
5.1  32     78.8    58
4.5  31.5   74      NaN
2.1  33.9   74.7    64
5.1  30.8   79.1    33
1.1  32.6   78.2    78
NaN  33.3   76      36
5.2  32.7   79.5    36
NaN  33.6   78.6    NaN

我想用 Lon in X-Axis Lat in Y-axis 制作散点图,并根据 Magnitude 中的值范围散布不同大小的点;

size =1 : Magnitude<2 ,  size =1.5 : 2<Magnitude<3,  size =2 : 3<Magnitude<4,  size =2.5 : Magnitude>4.

并根据深度值的范围使用不同的颜色;

 color =red : Depth<30 ,  color =blue : 30<Depth<40,  color =black : 40<Depth<60,   color =yellow : Depth>60

我想通过为尺寸和颜色定义一个字典来解决这个问题。 (只是给出想法;需要正确的语法)

更喜欢

def magnitude_size(df.Magnitude):
    if df.Magnitude < 2 :
        return 1
    if df.Magnitude > 2 and df.Magnitude < 3 :
        return 1.5
    if df.Magnitude > 3 and df.Magnitude < 4 :
        return 2
    if df.Magnitude > 4  :
        return 2.5


def depth_color(df.Depth):
    if df.Depth < 30 :
        return 'red'
    if df.Depth > 30 and df.Depth < 40 :
        return 'blue'
    if df.Depth > 40 and df.Depth < 60 :
        return 'black'
    if df.Depth > 60  :
        return 'yellow'


di = {
    'size': magnitude_size(df.Magnitude),
    'color' : depth_color(df.Depth)
}

plt.scatter(df.Lon,df.Lat,c=di['color'],s=di['size'])

plt.show()

如果 Magnitude 中有任何 NaN 值,则为散点提供不同的符号 (),如果 Depth 中有任何 NaN 值,则给出不同的颜色 (绿色)*

需要帮助

你可以使用 pandas.cut to create a couple of helper columns in df based on your color and size mappings. This should make it easier to pass these arguments to pyplot.scatter.

N.B。值得注意的是,您为大小选择的值可能无法很好地区分绘图中的标记 - 值得尝试不同的大小,直到获得所需的结果

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

df['color'] = pd.cut(df['Depth'], bins=[-np.inf, 30, 40, 60, np.inf], labels=['red', 'blue', 'black', 'yellow'])
df['size'] = pd.cut(df['Magnitude'], bins=[-np.inf, 2, 3, 4, np.inf], labels=[1, 1.5, 2, 2.5])

plt.scatter(df['Lon'], df['Lat'], c=df['color'], s=df['size'])


更新

这不是我推荐的,但如果你坚持使用 dictfunctions 那么请使用:

def magnitude_size(magnitude):
    if magnitude < 2 :
        return 1
    if magnitude >= 2 and magnitude < 3 :
        return 1.5
    if magnitude >= 3 and magnitude < 4 :
        return 2
    if magnitude >= 4  :
        return 2.5


def depth_color(depth):
    if depth < 30 :
        return 'red'
    if depth >= 30 and depth < 40 :
        return 'blue'
    if depth >= 40 and depth < 60 :
        return 'black'
    if depth >= 60  :
        return 'yellow'
    if np.isnan(depth):
        return 'green'

di = {
    'size': df.Magnitude.apply(magnitude_size),
    'color' : df.Depth.apply(depth_color)
}

plt.scatter(df.Lon,df.Lat,c=di['color'],s=di['size'])