根据 x 轴刻度定义条形宽度

根据 x 轴刻度定义条形宽度

我希望能够根据 x 轴刻度定义条形图的条形宽度。例如,如果 x 介于 0 和 4 之间,我希望将条形宽度设置为 1(x 轴的四分之一)。

答案1

由于您的问题不是 100% 确定(至少对我来说),我希望您正在搜索以下内容。

% used PGFPlots v1.17
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
    % use this `compat` level or higher so also absolute `bar width` values are allowed
    % (otherwise values without units will be interpreted in `pt`s.)
    \pgfplotsset{compat=1.7}
\begin{document}
\begin{tikzpicture}[
    /pgf/declare function={
        xmin = 0;
        xmax = 4;
        % change the `3.5` to your needs
        BarWidth = ifthenelse(xmax-xmin > 3.5, 1, 0.5);
    },
]
    \begin{axis}[
        xmin=xmin,
        xmax=xmax,
        ybar,
        enlarge x limits={abs=0.5},
        bar width=BarWidth,
    ]
        \addplot table {
            x   y
            0   0.5
            1   1
            2   2
            3   3
            4   4
            5   5
        };
    \end{axis}
\end{tikzpicture}
\end{document}

该图显示了上述代码的结果

答案2

这里有一个后续问题。我还想根据 x 轴长度而不是厘米来定义条形的水平偏移,以便我可以完美地重叠列的边缘

\documentclass[10pt]{article}

\usepackage{pgfplots}
\usepackage{tikz}
\usepackage{tikzscale}


\pgfplotsset{compat=1.15}

\makeatletter
\newcommand\resetstackedplots{
\makeatletter
\pgfplots@stacked@isfirstplottrue
\makeatother
\addplot [forget plot,draw=none] coordinates{(0.75,0) (1.5,0) (2.25,0)};
}
\makeatother


\begin{document}

\begin{tikzpicture}
\begin{axis}[
    /pgf/declare function={
    xmin = 0.25;
    xmax = 2.75;
    BarWidth = ifthenelse(xmax-xmin > 2.5, 0.25, 0.25);},
    ybar stacked,
    legend pos=north west,
    legend style={row sep=4pt},
    xtick pos=left,
    ytick pos=left,
    ybar=1pt,
    bar width=BarWidth,
    scale only axis=true, 
    xticklabels={AA,BB,CC},
    xtick={0.75,1.5,2.25},   
    xticklabel style={text height=2ex},
    xmin=0.25, xmax = 2.75,
    ymin=0]
    
    \addplot[ybar,fill=yellow, bar shift=-0.420cm] coordinates {
        (0.75,1)
        (1.5,1)
        (2.25,1)}; 
    \addplot[ybar,fill=red, bar shift=-0.420cm] coordinates {
        (0.75,2)
        (1.5,2)
        (2.25,1)};
    \addplot[ybar,fill=blue, bar shift=-0.420cm] coordinates {
        (0.75,3)
        (1.5,3)
        (2.25,3)};    
        
    \resetstackedplots      
   
    \addplot[ybar,fill=yellow, bar shift=+.420cm] coordinates {
        (0.75,3)
        (1.5,3)
        (2.25,3)}; 
    \addplot[ybar,fill=red, bar shift=+.420cm] coordinates {
        (0.75,3)
        (1.5,3)
        (2.25,3)};
    \addplot[ybar,fill=blue, bar shift=+.420cm] coordinates {
        (0.75,1)
        (1.5,1)
        (2.25,1)};       

\end{axis}
\end{tikzpicture}


\end{document}

在此处输入图片描述

相关内容