如何在保持纵横比不变的情况下缩小图形?
\documentclass[10pt]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x)= (\x >0) * (1+2^x) + (\x <= 0) * (-x^2-x+2)
;
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
axis line style={thick},
tick style={black, thick},
ymin=-2, ymax=5, ytick={-1,4}, ylabel=$y$,
xmin=-4, xmax=4, xtick={-3,-1,1,3}, xlabel=$x$,
domain=-4:3,samples=101,
]
\addplot [blue,thick] {func(x)};
\node at (-3.2, 2) {$\math{y=-x^2-ax+b}$};
\node at (2.8, 3.5) {$\math{y=2^x+1}$};
\begin{scriptsize}
\draw [fill=black] (0.,2.05) circle (2.2pt);
\draw[color=ffffff] (0.21,1.8) node {$2$};
\end{scriptsize}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
我必须进行大量修正和假设才能编译您的代码。当然,请删除\math
包装器。
为图表设置明确宽度的一种方法是将其包裹在\resizebox
包装器(由graphicx
包提供)或\scalebox
包装器(由adjustbox
包提供)中。
\documentclass[10pt]{article}
\usepackage{pgfplots,xcolor,graphicx}
\pgfplotsset{compat=1.15}
\begin{document}
\newcommand\mygraph{%
\begin{tikzpicture}[
declare function={
func(\x)= (x > 0) * (1+2^x) + (x <= 0) * (-x^2-x+2);
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
axis line style={thick},
tick style={black, thick},
ymin=-2, ymax=5, ytick={-1,4}, ylabel=$y$,
xmin=-4, xmax=4, xtick={-3,-1,1,3}, xlabel=$x$,
domain=-4:3,samples=101,
]
\addplot [blue,thick] {func(x)};
\node at (-2.4, 2.4) {$y=-x^2-x+2$};
\node at ( 2.5, 3.5) {$y=2^x+1$};
\begin{scriptsize}
\draw [fill=black] (0.,2.05) circle (2.2pt);
\draw[color=black] (0.21,1.8) node {$2$};
\end{scriptsize}
\end{axis}
\end{tikzpicture}}
\noindent
\mygraph % native size
\quad
\resizebox{4cm}{!}{\mygraph} % choose an explicit width, say, 4cm
\end{document}
答案2
正如我在评论中所说:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15} % recent is 1.18
\begin{document}
\begin{tikzpicture}[
declare function = {func(\x)=(\x>0)*(2^\x +1) + (\x<=0)*(-\x^2-\x+2 + 2);}
]
\begin{axis}[
width=6cm, % define width of image according to your needs
axis lines=middle,
axis line style={thick},
tick style={black, thick},
ymin=-2, ymax=5, ytick={-1, 2,4}, ylabel=$y$,
xmin=-4, xmax=4, xtick={-3,-1,1,3}, xlabel=$x$,
ticklabel style={font=\footnotesize},
domain=-4:3, samples=301
]
\addplot +[thick, no marks] {func(x)};
\addplot [black,mark=*] coordinates {(0,2)};
\node[left] at (0, 3) {$y=-x^2-ax+b$};
\node[right] at (1, 2) {$y=2^x+1$};
\end{axis}
\end{tikzpicture}
\end{document}