尝试向Seaborn散点图添加颜色条

2024-06-12 05:58:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名地质学硕士生,正在写我的论文,主要研究南太平洋许多火山的二氧化硫排放量。我对R有一点经验,但我的主管推荐python(特别是JupyterLab)用于生成图形和数据操作,因此我对编程相当陌生,基本上是边编程边自学。我试图使用地震数据生成一些使用seaborn的散点图,但我似乎无法在图例中显示地震震级的颜色条。下面是我正在使用的代码,我将尽我所能以清晰的方式格式化它

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy import stats
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt

然后是我正在处理的数据集。这些是地震数据集

df = pd.read_csv('Vanuatu Earthquakes May18-May19.csv')
df = pd.read_csv('Vanuatu Earthquakes May17-May18.csv')
df = pd.read_csv('Vanuatu Earthquakes May19-Jul20.csv')

还有火山的位置,纯粹是为了空间参考

dg = pd.read_csv('Volcano coordinates.csv')

这是我目前试图处理的主要情节。到目前为止,我已经能够使用色调函数对地震震级进行分类,但我不喜欢它在图例中的外观,我想将其转换为颜色条(或者使用颜色条而不是色调,或者/或者),除非我不太清楚如何做。或者,如果有一个不同的函数可以给出我想要的结果,我肯定会接受它,而不是散点图。此外,黑色三角形是火山,所以现在可以忽略这些

plt.figure(figsize=(5.5,9))
sns.scatterplot(x='longitude', y='latitude', data=df, 
                marker='D', hue='mag', palette='colorblind', cmap='RdBu')
sns.scatterplot(x='longitude', y='latitude', data=dg, 
                marker='^', legend='brief', color='k', s=100)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., title='Magnitude (Mw)')
plt.xlabel('Longitude (degrees)')
plt.ylabel('Latitude (degrees)')
plt.title('Earthquake and Volcano Locations', size=15)
plt.show()

image

希望这是足够清楚,但让我知道如果更多的信息是必要的


Tags: csv数据importdfread颜色as编程
1条回答
网友
1楼 · 发布于 2024-06-12 05:58:03

this answer中使用的关于Seaborn Barplot的相同方法也可以应用于散点图。您的代码看起来像这样:

# ...
norm = plt.Normalize(df['mag'].min(), df['mag'].max())
sm = plt.cm.ScalarMappable(cmap="RdBu", norm=norm)
sm.set_array([])

ax = sns.scatterplot(x='longitude', y='latitude', data=df, marker='D', palette='RdBu', hue='mag')
sns.scatterplot(x='longitude', y='latitude', data=dg, marker='^', 
                legend='brief', color='k', s=100, ax=ax)

# Remove the legend and add a colorbar (optional)
# ax.get_legend().remove()
# ax.figure.colorbar(sm)

# ...

有关操作颜色栏的标签和记号的信息,请参见this question及其答案

有关使用tips数据集的完整示例:

import seaborn as sns
import matplotlib.pyplot as plt

sns.set()
tips = sns.load_dataset("tips")
ax = sns.scatterplot(x="total_bill", y="tip", hue="size", palette='RdBu', data=tips)

norm = plt.Normalize(tips['size'].min(), tips['size'].max())
sm = plt.cm.ScalarMappable(cmap="RdBu", norm=norm)
sm.set_array([])

# Remove the legend and add a colorbar
ax.get_legend().remove()
ax.figure.colorbar(sm)

plt.show()

enter image description here

相关问题 更多 >