PGFPLOTS - 创建带有不同颜色条形图的条形图

PGFPLOTS - 创建带有不同颜色条形图的条形图

我想创建一个条形图,其中的条形具有不同的颜色。我的条形图如下:

在此处输入图片描述

我已经阅读过类似问题的解决方案,但我无法绘制我想要的内容。

我的代码如下:

\documentclass[a4paper, 12pt]{article}

\usepackage[paperwidth=5in, paperheight=3.2in]{geometry}
\usepackage{pgfplots}

\pgfplotsset{compat=newest}
\geometry{left=0mm, right=3mm,top=6mm, bottom=3mm,}


\begin{document}


\definecolor{mygr}{HTML}{e6e6e6}


\begin{figure}[!t]
\centering{
\begin{tikzpicture}

\begin{axis}[/pgf/number format/1000 sep={},
width=3.8in,
height=1.8in,
at={(0.758in,0.981in)},
scale only axis,
bar shift auto,
clip=false,
separate axis lines,
every outer x axis line/.append style={black},
every x tick label/.append style={font=\color{black}},
every x tick/.append style={black},
xmin=0,
xmax=5,
xtick={1,2,3,4},
ytick={0,500,1000, 2000},
xticklabels={\empty},
every outer y axis line/.append style={black},
every y tick label/.append style={font=\color{black}},
every y tick/.append style={black},
ymin=0,
ymax=2000,
ylabel={YYY},
axis background/.style={fill=white}]

\addplot[ybar, bar width=0.2, fill=mygr, draw=black] table[row sep=crcr] {%
1   500  \\ 
2   1000  \\ 
3   1200   \\ 
4   1800   \\ 
};

\node[below left, align=right, rotate=0]
at (rel axis cs:0.308,-0.001) {GREEN};
\node[below left, align=right, rotate=0]
at (rel axis cs:0.488,-0.001) {BLUE};
\node[below left, align=right, rotate=0]
at (rel axis cs:0.690,-0.001) {GREY};
\node[below left, align=right, rotate=0]
at (rel axis cs:0.868,-0.001) {RED};

\end{axis}

\end{tikzpicture}}
\end{figure}

\end{document}

任何帮助都将不胜感激。提前致谢!

答案1

您可以\addplot为每个栏目使用一个命令。但您必须设置bar shift=0pt

\documentclass[a4paper, 12pt]{article}
\usepackage[paperwidth=5in, paperheight=3.2in]{geometry}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\geometry{left=0mm, right=3mm,top=6mm, bottom=3mm,}

\definecolor{mygr}{HTML}{e6e6e6}
\begin{document}
\begin{figure}[!t]
  \centering
  \begin{tikzpicture}
    \begin{axis}[
        /pgf/number format/1000 sep={},
        width=3.8in,
        height=1.8in,
        at={(0.758in,0.981in)},
        scale only axis,
        clip=false,
        separate axis lines,
        axis on top,
        xmin=0,
        xmax=5,
        xtick={1,2,3,4},
        x tick style={draw=none},
        xticklabels={GREEN,BLUE,GREY,RED},
        ytick={0,500,1000, 2000},
        ymin=0,
        ymax=2000,
        ylabel={YYY},
        every axis plot/.append style={
          ybar,
          bar width=.2,
          bar shift=0pt,
          fill
        }
      ]
      \addplot[green]coordinates {(1,500)};
      \addplot[blue]coordinates{(2,1000)};
      \addplot[mygr]coordinates{(3,1200)};
      \addplot[red]coordinates{(4,1800)};
    \end{axis}
  \end{tikzpicture}
\end{figure}
\end{document}

结果

在此处输入图片描述

相关内容