- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
目前 seaborn 优惠functionality for split violinplots根据 hue
变量设置 split=True
。我想制作一个“半” fiddle 情节,即省略每把 fiddle 一半的情节。这样的图描绘了类似于每个连续变量的 pdf 的东西,仅绘制在每个分类变量的每条垂直线的一侧。
我已经设法欺骗 seaborn
用一个超出绘制值范围的额外数据点和一个额外的虚拟色调来绘制它,但我想知道这是否可以在不实际改变的情况下完成数据集,例如在 sns.violinplot()
参数中。
例如,这张图:
由以下片段创建:
# imports
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# load dataset from seaborn
datalist = sns.get_dataset_names()
dataset_name = 'iris'
if dataset_name in datalist:
df = sns.load_dataset(dataset_name)
else:
print("Dataset with name: " + dataset_name + " was not found in the available datasets online by seaborn.")
# prepare data
df2 = df.append([-999,-999,-999,-999,'setosa'])
df2['huecol'] = 0.0
df2['huecol'].iloc[-1]= -999
# plot
fig = plt.figure(figsize=(6,6))
sns.violinplot(x='species',y="sepal_width",
split=True, hue ='huecol', inner = 'quartile',
palette="pastel", data=df2, legend=False)
plt.title('iris')
# remove hue legend
leg = plt.gca().legend()
leg.remove()
plt.ylim([1,5.0])
plt.show()
最佳答案
我一直在寻找与此类似的解决方案,但没有找到令人满意的解决方案。我最后调用seaborn.kdeplot多次,因为 violinplot 本质上是一个单侧核密度图。
categorical_kde_plot
的函数定义如下
categorical_kde_plot(
df,
variable="tip",
category="day",
category_order=["Thur", "Fri", "Sat", "Sun"],
horizontal=False,
)
使用horizontal=True
,输出看起来像:
import seaborn as sns
from matplotlib import pyplot as plt
def categorical_kde_plot(
df,
variable,
category,
category_order=None,
horizontal=False,
rug=True,
figsize=None,
):
"""Draw a categorical KDE plot
Parameters
----------
df: pd.DataFrame
The data to plot
variable: str
The column in the `df` to plot (continuous variable)
category: str
The column in the `df` to use for grouping (categorical variable)
horizontal: bool
If True, draw density plots horizontally. Otherwise, draw them
vertically.
rug: bool
If True, add also a sns.rugplot.
figsize: tuple or None
If None, use default figsize of (7, 1*len(categories))
If tuple, use that figsize. Given to plt.subplots as an argument.
"""
if category_order is None:
categories = list(df[category].unique())
else:
categories = category_order[:]
figsize = (7, 1.0 * len(categories))
fig, axes = plt.subplots(
nrows=len(categories) if horizontal else 1,
ncols=1 if horizontal else len(categories),
figsize=figsize[::-1] if not horizontal else figsize,
sharex=horizontal,
sharey=not horizontal,
)
for i, (cat, ax) in enumerate(zip(categories, axes)):
sns.kdeplot(
data=df[df[category] == cat],
x=variable if horizontal else None,
y=None if horizontal else variable,
# kde kwargs
bw_adjust=0.5,
clip_on=False,
fill=True,
alpha=1,
linewidth=1.5,
ax=ax,
color="lightslategray",
)
keep_variable_axis = (i == len(fig.axes) - 1) if horizontal else (i == 0)
if rug:
sns.rugplot(
data=df[df[category] == cat],
x=variable if horizontal else None,
y=None if horizontal else variable,
ax=ax,
color="black",
height=0.025 if keep_variable_axis else 0.04,
)
_format_axis(
ax,
cat,
horizontal,
keep_variable_axis=keep_variable_axis,
)
plt.tight_layout()
plt.show()
def _format_axis(ax, category, horizontal=False, keep_variable_axis=True):
# Remove the axis lines
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
if horizontal:
ax.set_ylabel(None)
lim = ax.get_ylim()
ax.set_yticks([(lim[0] + lim[1]) / 2])
ax.set_yticklabels([category])
if not keep_variable_axis:
ax.get_xaxis().set_visible(False)
ax.spines["bottom"].set_visible(False)
else:
ax.set_xlabel(None)
lim = ax.get_xlim()
ax.set_xticks([(lim[0] + lim[1]) / 2])
ax.set_xticklabels([category])
if not keep_variable_axis:
ax.get_yaxis().set_visible(False)
ax.spines["left"].set_visible(False)
if __name__ == "__main__":
df = sns.load_dataset("tips")
categorical_kde_plot(
df,
variable="tip",
category="day",
category_order=["Thur", "Fri", "Sat", "Sun"],
horizontal=True,
)
关于python - 一半(不是 split !)seaborn 中的 fiddle 情节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53872439/
如何从 seaborn 生成的热图中隐藏颜色条 import numpy as np; np.random.seed(0) import seaborn as sns; sns.set_theme()
我正在尝试使用 seaborn 制作热图,但被困在更改特定值的颜色。假设值 0 应该是白色,值 1 应该是灰色,然后使用 cmap 提供的调色板。 试图使用面具,但感到困惑。 import matpl
我想改变散点的大小。 这些都不起作用: sns.relplot(x='columnx', y='columny', hue='cluster', data=df) sns.relplot(x='col
这个问题在这里已经有了答案: What is y axis in seaborn distplot? (3 个答案) 关闭 3 年前。 我正在使用以下语句绘制分布图: a = sns.distplo
我注意到 sns.barplot 使用标准错误作为误差条默认 1 。有办法把它改成SD吗? ax = sns.barplot(x="day", y="tip", data=tips, ci=???)
向 seaborn FacetGrid 中的每个直方图添加表示平均值(或其他集中趋势度量)的点和可变性度量(例如,标准偏差或置信区间)的最佳方法是什么? 结果应该类似于显示的图 here ,但在每个
我正在尝试使用 sns.histplot() 而不是 sns.distplot() 因为我在 colab 中收到以下消息: FutureWarning: distplot is a deprecate
我想绘制 3 个水平条形图,标签作为 y 轴,数据作为 x 轴,我希望每个图都是不同的颜色,并有某种类型的注释,例如星号,这取决于关于数据中某列所表示的重要性,例如: dat = pd.DataFra
根据 seaborn 文档 here seaborn.distplot()已被弃用,向前支持的图是:seaborn.displot()和 seaborn.histplot() . 但是,当我尝试使用
为了使 seaborn.pairplot() 正常工作,在 jupyter notebook 中执行了以下步骤。 /usr/local/lib/python2.7/site-packages/matp
使用 pandas 数据框绘制混淆矩阵时 y 轴两端被切一半? 这就是我得到的: 我使用了这里的代码How can I plot a confusion matrix?使用 pandas 数据框: i
您好,我刚刚为 seaborn 热图创建了自定义 cmap,但是当我想使用它时,它没有显示正确的颜色。我已经一步一步完成了: import seaborn as sns import numpy as
亲爱的,我正在尝试将 kaggle 教程代码应用于 Iris 数据集。 不幸的是,当我执行图表的代码时,我只能看到这个输出而看不到任何图表: matplotlib.axes._subplots.Axe
这个问题在这里已经有了答案: Seaborn plots in a loop (6 个答案) How to plot in multiple subplots (12 个答案) 关闭 1 年前。 我
我正在尝试在 python 中使用 seaborn 绘制直方图。但它给我的只是一个空白数字。 这是我专栏的describe(): 代码: plt.subplots(figsize=(7,7)) sns
如何在seaborn.lineplot中分别设置标记和线条的透明度? 我有一组点,我想画一条连接所有点的线图。我希望线条比标记更透明。如何做到这一点? 这是我的目标: 这是我的代码: import m
我正在使用 seaborn 库在 python 中绘制热图。数据框包含一些缺失值 (NaN)。我希望与这些字段对应的热图单元格是白色的(默认情况下)并且还用字符串 NA 进行注释。但是,如果我看对了,
如何对这个图进行排序以从大到小显示?我尝试使用 sort_values 但不起作用 plt.figure(figsize=(15,8)) sns.countplot(x='arrival_date_m
我的目标是在使用 seaborn 绘制的图上的 y = 0 上绘制一条水平红线:sns.lmplot由 col= 分割或 row= . import numpy as np, seaborn as s
我正在使用seaborn pairplot绘制我的数据点不同维度的散点图。但是,我希望数据点的标记具有与数据点的维度之一相对应的大小。我有以下代码: markersize = 1000* my_dat
我是一名优秀的程序员,十分优秀!