You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将LaTeX TikZ小提琴图调整为垂直方向?

垂直方向小提琴图的LaTeX实现方案

原代码生成的是横向小提琴图,若直接用scope的倾斜变换会扭曲图形,以下是调整为垂直方向的可行方案:

修改后的完整代码

\begin{filecontents*}{data1.dat}
5   1
6   1
3   1
3   1
7   1
8   1
3   1
8   1
7   1
9   1
5   1
\end{filecontents*}
\begin{filecontents*}{data2.dat}
12  2
14  2
12  2
8   2
22  2
22  2
12  2
12  2
7   2
12  2
2   2
\end{filecontents*}
\begin{filecontents*}{data3.dat}
20  3
20  3
21  3
20  3
22  3
21  3
20  3
24  3
22  3
21  3
20  3
\end{filecontents*}
\documentclass[tikz, border=1 cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepgfplotslibrary{fillbetween}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=0, xmax=4,
ymin=0, ymax=25,
xtick={1,2,3},
xticklabels={Condition 1, Condition 2, Condition 3},
]
\addplot[draw=none] gnuplot[raw gnuplot] {
plot 0; % 避免空绘图警告
set table "kdensity1.dat";
plot "data1.dat" using 2:1 smooth kdensity bandwidth 1.;
unset table;
set table "kdensity2.dat";
plot "data2.dat" using 2:1 smooth kdensity bandwidth 1.;
unset table;
set table "kdensity3.dat";
plot "data3.dat" using 2:1 smooth kdensity bandwidth 1.;
unset table;
};

\addplot[draw=none, name path=p1, x filter/.expression={1+0.1*y}] table {kdensity1.dat};
\addplot[draw=none, name path=m1, x filter/.expression={1-0.1*y}] table {kdensity1.dat};
\addplot[red!50] fill between [of=p1 and m1];

\addplot[draw=none, name path=p2, x filter/.expression={2+0.1*y}] table {kdensity2.dat};
\addplot[draw=none, name path=m2, x filter/.expression={2-0.1*y}] table {kdensity2.dat};
\addplot[green!50] fill between [of=p2 and m2];

\addplot[draw=none, name path=p3, x filter/.expression={3+0.1*y}] table {kdensity3.dat};
\addplot[draw=none, name path=m3, x filter/.expression={3-0.1*y}] table {kdensity3.dat};
\addplot[blue!50] fill between [of=p3 and m3];

\end{axis}
\end{tikzpicture}
\end{document}

关键修改说明

  • 核密度计算维度调整:将gnuplot中using 1:2改为using 2:1,让核密度沿Y轴(数据值方向)计算,匹配垂直布局需求
  • 轴配置交换:
    • 调整xmin/xmax为类别范围(0-4),ymin/ymax为数据值范围(0-25)
    • 将ytick/yticklabels改为xtick/xticklabels,让类别标签显示在X轴
  • 过滤表达式修改:把y filter替换为x filter,并调整表达式,让密度分布沿X轴(类别轴)两侧展开,形成垂直的小提琴形状

内容的提问来源于stack exchange,提问作者catbow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 12:04:51