我正在尝试使用以下代码创建一个简单的图表:
\begin{tikzpicture}
\begin{axis}[
symbolic x coords={
Integrated Circuits,
Transistors,
Capacitors,
Resistors,
Hybrid Circuits,
Diodes,
Others,
Solder Joints
},
xtick=data
]
\addplot[ybar,fill=blue] coordinates {
(Integrated Circuits, 27)
(Transistors, 14)
(Capacitors, 12)
(Resistors, 12)
(Hybrid Circuits, 12)
(Diodes, 10)
(Others, 10)
(Solder Joints, 3)
};
\end{axis}
\end{tikzpicture}
由于标签很长,因此显示如下:
如何在此图表的右侧创建图例并为条形和图例添加独特的颜色。
我有另一个想法,那就是保持不变,但垂直呈现图表下方的文本
答案1
您可能喜欢倾斜的 x 刻度标签:
\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\newlength{\TL} % Tick Label
\begin{document}
\begin{figure}[htb]
\settowidth{\TL}{\footnotesize Integrated}
\begin{tikzpicture}
\begin{axis}[
width = \linewidth,
symbolic x coords = {Integrated Circuits, Transistors, Capacitors,
Resistors, Hybrid Circuits, Diodes, Others,
Solder Joints},
bar width=11mm,
ybar,
xtick=data,
ticklabel style = {font=\footnotesize,
inner ysep=0pt},
xticklabel style = {text width=\TL, align=right,
anchor=north east, rotate=30},
legend entries={whatever} % default position is north east
]
\addplot coordinates {
(Integrated Circuits, 27)
(Transistors, 14)
(Capacitors, 12)
(Resistors, 12)
(Hybrid Circuits, 12)
(Diodes, 10)
(Others, 10)
(Solder Joints, 3)
};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}
答案2
通过这篇文章x 刻度标签的替代位置,通过增加
width
图表和\small
字体对于图例,我删除了
addplot
ybar, fill=blue
并添加ybar
了axis environment
\documentclass[12pt,a4paper]{article} %https://tex.stackexchange.com/questions/698728/how-to-add-color-and-legends-to-bar-chart \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[ symbolic x coords={ Integrated Circuits, Transistors, Capacitors, Resistors, Hybrid Circuits, Diodes, Others, Solder Joints }, ybar,%<--- added xtick=data, width=15cm, %https://tex.stackexchange.com/questions/296532/alternate-position-of-x-tick-labels x tick label style={ font=\small, yshift={-mod(\ticknum,2)*1em} }, legend entries={I don't know}, % legend style={at={(0.5,-0.15)}, % anchor=north,legend columns=-1}, ] % \addplot [ybar, fill=blue]coordinates { \addplot coordinates { (Integrated Circuits, 27) (Transistors, 14) (Capacitors, 12) (Resistors, 12) (Hybrid Circuits, 12) (Diodes, 10) (Others, 10) (Solder Joints, 3) }; \end{axis} \end{tikzpicture} \end{document}