python - 尝试将颜色条添加到 Seaborn 散点图

标签 python matplotlib seaborn scatter-plot colormap

我是一名地质学硕士生,正在撰写我的论文,重点是南太平洋许多火山的二氧化硫输出。我对 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
希望这足够清楚,但如果需要更多信息,请告诉我!

最佳答案

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

# ...
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

关于python - 尝试将颜色条添加到 Seaborn 散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62884183/

相关文章:

python - Pandas - 计算具有可变窗口大小的滚动累积乘积

python - 正确读取/绘制由 '>' 分隔的数据

python - MatPlotLib、日期时间和类型错误 : ufunc 'isfinite' not supported for the input types…

Python matplotlib开罗错误

python - 带有圆圈表示人口规模的热图

python - 使用 Flask 的 StackDriver 错误报告中未显示 Google App Engine 错误

java - Jython 中的 Python 解释器

python - 如何根据名称为单个条形着色

python - Seaborn 条形图按条形长度排序

python - python Bottle框架如何通过装饰器安装路由处理程序?