我有以下代码。
\documentclass[a4paper,twoside,12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}
\usepackage[english]{babel}
\usepackage{pgfplotstable}
\definecolor{color1}{rgb}{0.98, 0.81, 0.69}
\definecolor{color2}{rgb}{0.55, 0.71, 0.0}
\definecolor{color3}{rgb}{1.0, 0.6, 0.4}
\definecolor{color4}{rgb}{0.29, 0.59, 0.82}
\pgfplotscreateplotcyclelist{mycolor}{
{fill=color1!80, draw=color1},
{fill=color2!80, draw=color2},
{fill=color3!80, draw=color3},
{fill=color4!80, draw=color4},
}
\begin{filecontents*}{coefficienti.dat}
T K Q Kf n
400 0.0463 32.9 5.78 0.321
500 0.124 24.8 6.30 0.275
600 0.115 24.6 6.30 0.261
700 1.64 24.4 11.9 0.151
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis} [
ymin=0,
ybar=0, bar width=20, bar shift=0,
xtick={1,2,3,4},
xticklabels from table={coefficienti.dat}{T},
ymajorgrids=true,
cycle list name=mycolor,
nodes near coords,
every node near coord/.append style = {
/pgf/number format/.cd,
fixed,
fixed zerofill,
precision=3
}]
\addplot table [x=T,y=K] {coefficienti.dat};
\end{axis}
\end{tikzpicture}
\end{document}
结果是下面的图表(不要介意颜色,我知道这很糟糕)。
我希望列表中的每个栏都有不同的颜色
mycolor
。我该怎么做?我想在 x 轴上放置表格 T 列的值
coefficienti.dat
。我该怎么做?
答案1
下面是使用循环和过滤器的一个选项(discard if not
在Jake's answer
到条形图中各个条形的颜色不同并添加条形标签(英文):
由于xtick=data
仅在第一个图上放置数据标签,因此第一个图被排除在循环之外以获取所有标签:
\documentclass[a4paper,twoside,12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8x]{inputenc}
\usepackage[english]{babel}
\usepackage{pgfplotstable}
\definecolor{color1}{rgb}{0.98, 0.81, 0.69}
\definecolor{color2}{rgb}{0.55, 0.71, 0.0}
\definecolor{color3}{rgb}{1.0, 0.6, 0.4}
\definecolor{color4}{rgb}{0.29, 0.59, 0.82}
\pgfplotscreateplotcyclelist{mycolor}{
{fill=color1!80, draw=color1},
{fill=color2!80, draw=color2},
{fill=color3!80, draw=color3},
{fill=color4!80, draw=color4},
}
\pgfplotsset{
discard if/.style 2 args={
x filter/.code={
\ifdim\thisrow{#1} pt=#2pt
\def\pgfmathresult{inf}
\fi
}
},
discard if not/.style 2 args={
x filter/.code={
\ifdim\thisrow{#1} pt=#2pt
\else
\def\pgfmathresult{inf}
\fi
}
}
}
\begin{filecontents*}{coefficienti.dat}
T K Q Kf n
400 0.0463 32.9 5.78 0.321
500 0.124 24.8 6.30 0.275
600 0.115 24.6 6.30 0.261
700 1.64 24.4 11.9 0.151
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis} [
ymin=0,
ybar=0, bar width=20, bar shift=0,
xtick={data},
ymajorgrids=true,
cycle list name=mycolor,
nodes near coords,
every node near coord/.append style = {
/pgf/number format/.cd,
fixed,
fixed zerofill,
precision=3
}]
% first complete plot to place the x-axis labels
\addplot+ table[x=T,y=K] {coefficienti.dat};
% the bars with different colors
\pgfplotsinvokeforeach{500,600,700}{
\addplot+[discard if not={T}{#1}] table[x=T,y=K] {coefficienti.dat};
}
\end{axis}
\end{tikzpicture}
\end{document}