如何绘制海底山脊图 [英] How to plot a seaborn ridge plot

查看:39
本文介绍了如何绘制海底山脊图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 seaborn 0.11,我想绘制一个 数据.这是我期望的示例.

这些是不同角度的光谱数据.有什么办法可以在python中绘制类似的东西吗?预先感谢.

 将matplotlib.pyplot导入为pltdata = np.loadtxt("0_deg.txt",skirows = 0,dtype = np.float128)无花果,ax = plt.subplots(figsize =(8,6))ax.plot(数据,标记大小=1,标签=0°")

数据看起来像这样

解决方案

更新之前

 将熊猫作为pd导入导入matplotlib.pyplot作为plt从pathlib导入路径##########################################################如果从本地计算机加载数据,则使用#创建文件的路径p =路径('c:/somepathtofiles')# 如果从本地计算机加载数据#获取所有文件的生成器files = p.glob('*.44V*')#将文件加载到pandas.DataFrames的字典中dfd = {f'{file.suffix.split("_")[-1]}': pd.read_csv(file, sep='\\s+', header=None) for file in files}########################################################## 从 GitHub 加载数据时使用# 不要对文件使用这两行.文件 = [f'https://raw.githubusercontent.com/mahesh27dx/NPR/master/CuSo4_10mV_300mS_Amod9.44V_{v}deg' for v in range(0, 190, 10)]#将文件加载到pandas.DataFrames的字典中dfd = {f'{file.split("__")[-1]}':文件中文件的pd.read_csv(file,sep ='\\ s +',header = None)}########################################################### 遍历字典plt.figure(figsize =(10,8))#设置绘图对于 dfd.items() 中的 k, v:dfd[k].columns = ['mag_field', '强度']sns.lineplot(x ='mag_field',y ='intensity',data = v,label = k)plt.legend(bbox_to_anchor=(1.05, 1), loc='左上')plt.xlabel('磁场')plt.ylabel('场强度')plt.show()

Using seaborn 0.11, I'd like to plot a seaborn ridge plot

I want to plot the magnetic spectrum data in a single plot. So the y-axis counts only the number of plots and x-axis uses the data. Here is an example of what I'm expecting.

These are the spectrum data for different angles. Are there any ways to plot something like this in python? Thanks in advance.

import matplotlib.pyplot as plt

data = np.loadtxt("0_deg.txt", skiprows=0, dtype=np.float128)
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(data, markersize=1, label="0° ")

Data looks like this

Data

269.09019   0.10781
269.09208   0.10908
269.09397   0.11928
269.09587   0.11800
269.09776   0.11418
269.09966   0.11545
269.10155   0.11928
269.10344   0.11673
269.10534   0.10781
269.10723   0.10526
269.10913   0.11418
269.11102   0.11418
269.11292   0.11291
269.11481   0.11928
269.11670   0.11928
269.11860   0.12055
269.12049   0.11928
269.12239   0.11928
269.12428   0.11673
269.12618   0.11545
269.12807   0.11545
269.12996   0.11036
269.13186   0.10908
269.13375   0.10144
269.13565   0.10908
269.13754   0.10654
269.13943   0.10399
269.14133   0.10526
269.14322   0.11418
269.14512   0.10908
269.14701   0.10272
269.14891   0.09889
269.15080   0.10526
269.15269   0.09889
269.15459   0.09635
269.15648   0.09889
269.15838   0.10017
269.16027   0.09507
269.16217   0.08998
269.16406   0.09507
269.16595   0.08870
269.16785   0.09252
269.16974   0.09762
269.17164   0.09889
269.17353   0.09507
269.17542   0.10017
269.17732   0.10399
269.17921   0.10144
269.18111   0.09762
269.18300   0.10144
269.18490   0.10144
269.18679   0.09635
269.18868   0.10017
269.19058   0.10399
269.19247   0.10017
269.19437   0.10017
269.19626   0.09889
269.19816   0.10017
269.20005   0.09507
269.20194   0.09635
269.20384   0.09380
269.20573   0.09252
269.20763   0.08998

解决方案

Ridge Plot

  • Use pathlib with .glob to find all the files in the directory
  • Load the files into a list of pandas.DataFrames
    • The filename is split on underscores, and uses the value at index -1 as the 'label' column value for each set of data. This value is 0deg, 10deg, etc.
      • The label for each file must be unique, because the plot row is determined by the label.
    • Given f = WindowsPath('data/CuSo4_10mV_300mS_Amod9.44V_0deg') as the pathlib object
      • f.suffix is '.44V_0deg'
      • f.suffix.split('_')[-1] is '0deg'
    • A 'label' column is added so the correct 'intensity' values can be identified for each plot line.
  • Use pandas.concat to combine the list of dataframes.
  • The DataFrame for a ridge plot must be in a long (tidy) format

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

sns.set_theme(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})

# find the local files
p = Path('c:/somepathtofiles')  # p = Path.cwd()  # for data in the current working directory
files = list(p.glob('*.44V*'))

# load all the data, but create a dataframe in the correct form for a RidgePlot
dfl = list()
for f in files:
    v = pd.read_csv(f, sep='\\s+', header=None, usecols=[1])
    v.columns = ['intensity']
    v['label'] = f.suffix.split('_')[-1]
    dfl.append(v)

# combine the list of dataframes into a single dataframe    
df = pd.concat(dfl)

# plot
# Initialize the FacetGrid object
pal = sns.cubehelix_palette(len(df.label.unique()), rot=-.25, light=.7)
g = sns.FacetGrid(df, row="label", hue="label", aspect=15, height=.5, palette=pal)

# Draw the densities in a few steps
g.map(sns.kdeplot, "intensity", bw_adjust=.5, clip_on=False, fill=True, alpha=1, linewidth=1.5)
g.map(sns.kdeplot, "intensity", clip_on=False, color="w", lw=2, bw_adjust=.5)
g.map(plt.axhline, y=0, lw=2, clip_on=False)

# Define and use a simple function to label the plot in axes coordinates
def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .2, label, fontweight="bold", color=color, ha="left", va="center", transform=ax.transAxes)

g.map(label, "intensity")

# Set the subplots to overlap
g.fig.subplots_adjust(hspace=-.25)

# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=True, left=True)

# uncomment the following line if there's a tight layout warning
# g.fig.tight_layout()

Before Update

import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path

###########################################################
# Use if loading the data from the local computer

# create the path to the files
p = Path('c:/somepathtofiles')

# if loading the data from the local computer
# get a generator of all the files
files = p.glob('*.44V*')

# load the files into a dict of pandas.DataFrames
dfd = {f'{file.suffix.split("_")[-1]}': pd.read_csv(file, sep='\\s+', header=None) for file in files}

###########################################################
# Use if loading data from GitHub

# don't use both lines for files.
files = [f'https://raw.githubusercontent.com/mahesh27dx/NPR/master/CuSo4_10mV_300mS_Amod9.44V_{v}deg' for v in range(0, 190, 10)]

# load the files into a dict of pandas.DataFrames
dfd = {f'{file.split("_")[-1]}': pd.read_csv(file, sep='\\s+', header=None) for file in files}

###########################################################

# iterate through the dict
plt.figure(figsize=(10, 8))  # set up plot figure
for k, v in dfd.items():
    dfd[k].columns = ['mag_field', 'intensity']

    sns.lineplot(x='mag_field', y='intensity', data=v, label=k)
    
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.xlabel('Magnetic Field')
plt.ylabel('Field Intensity')
plt.show()

这篇关于如何绘制海底山脊图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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