使用 \foreach 为图表中的辅助线分配编号时更改编号

使用 \foreach 为图表中的辅助线分配编号时更改编号
\documentclass[11pt]{article}
\usepackage{xfrac, array, tabu, multirow, graphicx, setspace, dcolumn, tikz}
\usepackage[fleqn]{mathtools}
\usepackage[ngerman]{babel}
\usepackage[applemac]{inputenc}
\begin{document}

 \definecolor{myblue}{HTML}{92dcec}
\begin{tikzpicture}
   \draw (0cm,0cm) -- (4cm,0cm);  %Abzisse
  \draw (0cm,0cm) -- (0cm,9cm);  %Ordinate
  \foreach \x in {2,4,6,8,10}  %Hilfslinien
    \draw[gray!50, text=black] (-0.2 cm,\x cm) -- (6 cm,\x cm) 
      node at (-0.5 cm,\x cm) {\x};  %Beschriftung der Hilfslinien
      \node at (7.5cm,5cm) {Balkendiagramm für Happy}; 
  \foreach \x/\y/\country in {0/5/1,  %\x ist Anfang der Säulen
                              2/9/2,  %\y ist Höhe der Säulen
                              4/1/3}
     {\draw[fill=myblue] (\x cm,0cm) rectangle (2cm+\x cm,\y cm); %die Säulen
     %  node at (1cm + \x cm,\y cm + 0.3cm) {\y}; %die Prozente über den Säulen
     \node[left] at (1cm +\x cm,-0.3cm) {\country}; %Säulenbeschriftung
    };\end
    {tikzpicture}

我想要做的是将编号从 改为 ,2/4/6/8/10同时4/8/12/16/20保持辅助线位于同一位置。我今天做了很多研究,但没能找到答案。

答案1

对于绘制图表,我认为最好使用直接基于 TikZ 构建的 PGFPlots,而不是“手工”绘制所有内容:

\documentclass[11pt]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\begin{document}

\definecolor{myblue}{HTML}{92dcec}

    \begin{tikzpicture}
    \begin{axis}[
            width=8cm, height=10cm,  % Overall dimensions of the plot
            ybar,   % Use vertical bar chart
            bar width=1,    % All bars are one data unit wide (requires \pgfplotsset{compat=1.8})
            ymin=0, ymax=20,    % Limits of the y axis
            ytick={0,5,...,20},
            enlarge x limits={abs=0.5}, % Extend the x axis by half a data unit on either end, so the bars are shown completely
            axis lines*=left,   % Axis lines only on the bottom and left
            xtick=data, % Only show x tick labels where there is a bar
            clip=false, % Avoid cutting off the edge of the bars
            ymajorgrids % Show horizontal grid lines
        ]
    \addplot [fill=myblue, draw=black] table {
    x y
    1 10
    2 18
    3 2
    };
    \end{axis}
    \end{tikzpicture}
\end{document}

如果您想继续使用代码,可以node使用直接在 内计算标签的值\the\numexpr\x*2\relax。请注意,这仅适用于整数运算。

\documentclass[11pt]{article}
\usepackage{tikz}

\begin{document}

\definecolor{myblue}{HTML}{92dcec}
\begin{tikzpicture}
\draw (0cm,0cm) -- (4cm,0cm);
\draw (0cm,0cm) -- (0cm,9cm);
\foreach \x in {2,4,6,8,10}{
    \draw[gray!50, text=black] (-0.2 cm,\x cm) -- (6 cm,\x cm) 
      node at (-0.5 cm,\x cm) {\the\numexpr\x*2\relax};
}
\foreach \x/\y/\country in {0/5/1,
                            2/9/2,
                            4/1/3}{
    \draw[fill=myblue] (\x cm,0cm) rectangle (2cm+\x cm,\y cm); 
    \node[left] at (1cm +\x cm,-0.3cm) {\country}; 
};
\end{tikzpicture}
\end{document}

相关内容