Skip to content

Instantly share code, notes, and snippets.

@vicapow
Created November 11, 2024 00:10
Show Gist options
  • Save vicapow/c70b59e398e565dacf29a6ce9ecca251 to your computer and use it in GitHub Desktop.
Save vicapow/c70b59e398e565dacf29a6ce9ecca251 to your computer and use it in GitHub Desktop.
Avoid overlapping axis labels and show correct legend item using `forget plot`
\documentclass{article}
\usepackage{pgfplots}
\usepackage{amsmath}
\pgfplotsset{compat=1.18}
\usepackage{pdflscape}
\begin{document}
\begin{landscape}
\pagestyle{empty}
\begin{tikzpicture}[scale=1]
\begin{axis}[
legend style={at={(1,1)},anchor=north east},
title={Temperature Data from 1990 to 2022},
xlabel={Year},
ylabel={Temperature (°C)},
grid=both,
major grid style={line width=.2pt,draw=gray!50},
minor grid style={line width=.1pt,draw=gray!10},
% Experment with adjusting the xmin from 1989 to 1990 and
% see that the point covers the y axis label
xmin=1989, xmax=2031,
ymin=22, ymax=31,
xtick={1990,1991, 1992, 1993,1994,1995, 1996, 1997,1998,1999, 2000,2001, 2002,2003, 2004,2005 ,2006, 2007,2008, 2009,2010,2011, 2012,2013, 2014,2015, 2016, 2017,2018, 2019,2020, 2021,2022,2030},
xticklabels={1990,1991, 1992,1993, 1994,1995, 1996, 1997,1998, 1999,2000, 2001,2002, 2003,2004, 2005,2006, 2007,2008, 2009,2010,2011,2012, 2013,2014, 2015,2016, 2017,2018, 2019,2020,2021, 2022,2030},
xticklabel style={rotate=90, anchor=north east},
ytick={20, 22,23, 24,25,26,27,28,29, 30,31},scatter,
mark options={scale=1.5},
width=15cm,
height=10cm,
x label style={at={(axis description cs:0.5,-0.13)},anchor=north},
]
% Use `forget plot` to "ignore" the plot in the legend later.
\addplot[only marks, blue, forget plot] coordinates {
(1990,25)(1991,24.6)(1992,24.1)(1993,24.2)(1994,28.2)(1995,25.1)(1996,24.9)(1997,25.3)(1998,26.3)(1999,25.2)(2000,27.2)(2001,22.5)(2002,27.1)(2003,25.5)(2004,26.1)(2005,27.1)(2006,27.7)(2007,27.6)(2008,24.4)(2009,27.3)(2010,25.9)(2011,26.9)(2012,27)(2013,27.1)(2014,25)(2015,30.3)(2016,26.6)(2017,26.1)(2018,28.6)(2019,29.1)(2020,25.5)(2021,26.2)(2022,26.5)(2030,28.10989)
};
% \addlegendimage]{black,dashed}; % Remove. Seemed extra?
\addplot[domain=1990:2030,no markers, dashed,black,thick] {(0.07503*(x) - 124.208)};
\addlegendentry{$y=0.0750334x - 124.208, R^2 = 0.2039$}
\addlegendentry{$y=0.0750334x - 124.208, R^2 = 0.2039$}
\end{axis}
\end{tikzpicture}
\end{landscape}
\end{document}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment