尝试将色标添加到Seaborn散点图中 [英] Trying to add a colorbar to a Seaborn scatterplot

查看:37
本文介绍了尝试将色标添加到Seaborn散点图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名地质学硕士生,正在撰写我的论文,重点是南太平洋一些火山的二氧化硫输出.我对R有一点经验,但是我的主管建议使用python(特别是JupyterLab)来生成图形和数据操作,因此我对编程非常陌生,并且基本上可以自学.我正在尝试使用地震数据使用 seaborn 生成一些散点图,但我似乎无法在图例中显示地震震级的颜色条.我正在使用的代码如下,我会尽力以清晰的方式对其进行格式化.

将pandas导入为pd将numpy导入为np将 seaborn 作为 sns 导入导入matplotlib.pyplot作为plt将Matplotlib导入为mpl来自 scipy 导入统计将 cartopy.crs 导入为 ccr将 cartopy.io.img_tiles 导入为 cimgt

然后使用我正在使用的数据集.这些是地震数据的集合.

  df = pd.read_csv('瓦努阿图地震May18-May19.csv')df = pd.read_csv('瓦努阿图地震 May17-May18.csv')df = pd.read_csv('瓦努阿图大地震May19-Jul20.csv')

和火山的位置,纯粹是为了空间参考.

dg = pd.read_csv('火山坐标.csv')

这是我目前正在尝试处理的主要情节.到目前为止,我已经能够使用色相函数对地震的震级进行分类,但是我不喜欢它在图例中的外观,而是希望将其转换为颜色条(或者使用颜色条代替色相,或者/或者).,除了我不太清楚如何做到这一点.另外,如果有一个不同的函数可以为我提供所需的结果,那么我肯定会对此表示欢迎,而不是使用散点图.另外黑色三角形是火山,所以现在可以忽略它们.

  plt.figure(figsize =(5.5,9))sns.scatterplot(x='经度', y='纬度', 数据=df,marker ='D',hue ='mag',palette ='colorblind',cmap ='RdBu')sns.scatterplot(x ='经度',y ='纬度',数据= dg,标记='^',图例='简短',颜色='k',s = 100)plt.legend(bbox_to_anchor =(1.05,1),loc = 2,borderaxespad = 0.,title ='幅值(Mw)')plt.xlabel('经度(度)')plt.ylabel('纬度(度)')plt.title('地震和火山位置', size=15)plt.show()

希望这很清楚,但请告知我是否需要更多信息!

解决方案

I'm a geology master's student working on my dissertation with a focus on the Sulfur Dioxide output of a number of volcanoes in the South Pacific. I have a little experience with R but my supervisor recommended python (JupyterLab specifically) for generating figures and data manipulation so I'm pretty new to programming and essentially teaching myself as I go. I'm trying to use earthquake data to generate some scatterplots using seaborn but I can't seem to get a color bar to show up in the legend for the earthquake magnitude. The code I'm using is below and I'll do my best to format it in a clear way.

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

then the data sets I'm working with. These are the sets for Earthquake data.

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

and locations of the volcanoes, purely there for spatial reference.

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

Here's the main plot I'm trying to work with as it stands at the moment. So far I've been able to classify the earthquakes' magnitudes using the hue function but I don't like how it looks in the legend and want to convert it to a colorbar (or use a colorbar instead of hue, either/or), except I can't quite figure out how to do that. Alternatively, if there's a different function that would give me the results I'm looking for, I'm definitely open to that instead of a scatterplot. Also the black triangles are the volcanoes so those can be ignored for now.

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

Hopefully that's clear enough but let me know if more info is needed!

解决方案

The same method employed in this answer regarding Seaborn barplots can be applied to a scatterplot as well. With your code that would look something like this:

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

# ...

See this question and its answers for information on manipulating the labels and ticks of the color bar.

For a complete example using the tips dataset:

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

这篇关于尝试将色标添加到Seaborn散点图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆