如何制作散点图大小和颜色变化的散点图,对应于数据帧中的值范围? 更新

我有一个数据框

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

我想在X轴上放置Lon在Y轴上绘制散点图,并根据Magnitude中的值范围来绘制具有不同大小的散点;

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

,并根据Depth中的值的范围使用不同的颜色;

 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()

如果“震级”中的NaN值给出了不同的散点符号(),如果“深度”中的NaN值给出了不同的颜色(绿色)*

需要帮助

namoral 回答:如何制作散点图大小和颜色变化的散点图,对应于数据帧中的值范围? 更新

您可以根据自己的dfcolor映射,使用pandas.cutsize中创建几个帮助器列。这样应该可以更轻松地将这些参数传递给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'],2,3,4,labels=[1,1.5,2.5])

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

enter image description here


更新

我不建议这样做,但是如果您坚持使用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'])
本文链接:https://www.f2er.com/3153968.html

大家都在问