diff --git a/README.md b/README.md index a9d07d5..f486944 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,10 @@ Beginner handout [(download pdf)](https://matplotlib.org/cheatsheets/handout-beg :-----------------------------------------------------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:----------------------------------------------------------------------------------: ![](https://matplotlib.org/cheatsheets/handout-beginner.png) | ![](https://matplotlib.org/cheatsheets/handout-intermediate.png) | ![](https://matplotlib.org/cheatsheets/handout-tips.png) +# Translations +This document is translated in the following languages: +* [Português Brasileiro](README.pt-br.md) + # For contributors to the cheatsheets ## How to compile diff --git a/README.pt-br.md b/README.pt-br.md new file mode 100644 index 0000000..422a7f5 --- /dev/null +++ b/README.pt-br.md @@ -0,0 +1,71 @@ +# Folhas de dicas para usuários do Matplotlib + +## Observação +O conteúdo original dessa folha de dicas é do repositório [oficial do +`matplotlib`](https://github.com/matplotlib/cheatsheets). Essa tradução +não-oficial visa tornar as dicas mais acessíveis para pessoas que usam a Matplotlib. + +Façam bom uso! + +## Folhas de dicas +Cheatsheet [(baixe o pdf)](https://matplotlib.org/cheatsheets/cheatsheets.pdf) | | +:------------------------------------------------------------------------------:|:----------------------------------------------------------: +![](https://matplotlib.org/cheatsheets/cheatsheets-1.png) | ![](https://matplotlib.org/cheatsheets/cheatsheets-2.png) + +## Folhetos + +Folheto iniciante [(download pdf)](https://matplotlib.org/cheatsheets/handout-beginner.pdf) | Folheto intermediário [(download pdf)](https://matplotlib.org/cheatsheets/handout-intermediate.pdf) | Folheto de dicas [(download pdf)](https://matplotlib.org/cheatsheets/handout-tips.pdf) +:-----------------------------------------------------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:----------------------------------------------------------------------------------: +![](https://matplotlib.org/cheatsheets/handout-beginner.png) | ![](https://matplotlib.org/cheatsheets/handout-intermediate.png) | ![](https://matplotlib.org/cheatsheets/handout-tips.png) + +# Para contribuidores das dicas + +## Como compilar + +1. Você precisa criar um repositório `fonts` com: + +* `fonts/roboto/*` : Veja https://fonts.google.com/specimen/Roboto + ou https://github.com/googlefonts/roboto/tree/master/src/hinted +* `fonts/roboto-slab/*` : Veja https://fonts.google.com/specimen/Roboto+Slab + ou https://github.com/googlefonts/robotoslab/tree/master/fonts/static +* `fonts/source-code-pro/*` : Veja https://fonts.google.com/specimen/Source+Code+Pro + ou https://github.com/adobe-fonts/source-code-pro/tree/release/OTF +* `fonts/source-sans-pro/*` : Veja https://fonts.google.com/specimen/Source+Sans+Pro + ou https://github.com/adobe-fonts/source-sans-pro/tree/release/OTF +* `fonts/source-serif-pro/*` : Veja https://fonts.google.com/specimen/Source+Serif+Pro + ou https://github.com/adobe-fonts/source-serif-pro/tree/release/OTF +* `fonts/eb-garamond/*` : Veja https://bitbucket.org/georgd/eb-garamond/src/master +* `fonts/pacifico/*` : Veja https://fonts.google.com/download?family=Pacifico + +No Linux, com o `make` instalado, as fontes podem ser configuradas com o seguinte comando: + +```shell +make -C fonts +``` + +As fontes podem ser descobertas pelo `matplotlib` (por via do `fontconfig`) ao +criar o arquivo `$HOME/.config/fontconfig/fonts.conf` com o seguinte conteúdo (veja [aqui](https://www.freedesktop.org/software/fontconfig/fontconfig-user.html)): + +```xml + + + +/path/to/cheatsheets/fonts/ +... + +``` + + +2. Você precisa gerar todas as figuras: + +``` +$ cd scripts +$ for script in *.py; do python $script; done +$ cd .. +``` + +3. Compile a folha +``` +$ xelatex cheatsheets.tex +$ xelatex cheatsheets.tex +``` diff --git a/cheatsheets.pt-br.tex b/cheatsheets.pt-br.tex new file mode 100644 index 0000000..6d72649 --- /dev/null +++ b/cheatsheets.pt-br.tex @@ -0,0 +1,1043 @@ +% ----------------------------------------------------------------------------- +% Matplotlib cheat sheet - Released under the BSD License +% ----------------------------------------------------------------------------- +\documentclass[10pt,landscape,a4paper]{article} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} + +% --- Page layout ------------------------------------------------------------- +\usepackage[right=2.5mm, left=2.5mm, top=2.5mm, bottom=2.5mm]{geometry} + +% --- English stuff ----------------------------------------------------------- +\usepackage[english]{babel} +\usepackage{xspace} +\usepackage{csquotes} + +% --- Graphics ---------------------------------------------------------------- +\usepackage{tikz} +\usepackage{graphicx} +\usepackage[percent]{overpic} +\graphicspath{{./figures/}{./icons/}{./logos/}} +\usepackage[export]{adjustbox} + +% --- Framed boxes ------------------------------------------------------------ +\usepackage[framemethod=TikZ]{mdframed} +\mdfsetup{skipabove=0pt,skipbelow=0pt} +\usepackage{menukeys} + +% --- URL, href and colors ---------------------------------------------------- +\usepackage{xcolor} +\colorlet{citecolor}{black} +\colorlet{linkcolor}{black} +\colorlet{urlcolor}{black} +\usepackage[ + bookmarks=true, + breaklinks=true, + pdfborder={0 0 0}, + citecolor=citecolor, + linkcolor=linkcolor, + urlcolor=urlcolor, + colorlinks=true, + linktocpage=false, + hyperindex=true, + colorlinks=true, + linktocpage=false, + linkbordercolor=white]{hyperref} + +% --- Tests ------------------------------------------------------------------- +\usepackage{etoolbox} + +% --- Fonts ------------------------------------------------------------------- +\usepackage{fontspec} +\usepackage[fixed]{fontawesome5} +\usepackage[babel=true]{microtype} +\defaultfontfeatures{Ligatures=TeX} +\setmainfont{Source Serif Pro}[ + Path = fonts/source-serif-pro/SourceSerifPro-, + Extension = .otf, + UprightFont = Light, + ItalicFont = LightIt, + BoldFont = Regular, + BoldItalicFont = It ] +\setsansfont{Roboto}[ + Path = fonts/roboto/Roboto-, + Extension = .ttf, + UprightFont = Light, + ItalicFont = LightItalic, + BoldFont = Regular ] +\setmonofont{Source Code Pro}[ + Path = fonts/source-code-pro/SourceCodePro-, + Extension = .otf, + UprightFont = Light, + BoldFont = Regular ] +\newfontfamily\RobotoCon{Roboto Condensed}[ + Path = fonts/roboto/RobotoCondensed-, + Extension = .ttf, + UprightFont = Regular, + ItalicFont = Italic, + BoldFont = Bold ] +\newfontfamily\RobotoSlab{Roboto Slab}[ + Path = fonts/roboto-slab/RobotoSlab-, + Extension = .ttf, + UprightFont = Light, + BoldFont = Regular ] +\newfontfamily\Roboto{Roboto}[ + Path = fonts/roboto/Roboto-, + Extension = .ttf, + UprightFont = Regular, + ItalicFont = Italic, + BoldFont = Black ] + +% --- Arrays ------------------------------------------------------------------ +\usepackage{multicol} +\usepackage{colortbl} +\usepackage{array, multirow} + +% --- Maths ------------------------------------------------------------------- +\usepackage{amsmath} + + +% --- PDF comments ------------------------------------------------------------ +\usepackage{pdfcomment} + +% --- Default options --------------------------------------------------------- +\setlength\parindent{0pt} +\setlength{\tabcolsep}{2pt} +\baselineskip=0pt +\setlength\columnsep{1.75mm} + + +% --- Macros ------------------------------------------------------------------ +\newcommand{\button}[1]{\tikz[baseline=(X.base)] + \node [fill=orange!40, rectangle, inner sep=2pt,rounded corners=1pt] (X) {#1};} + +\newcommand{\API}[1]{\tikz[baseline=(X.base)] + \node [fill=black!40, rectangle, inner sep=2pt,rounded corners=1pt] (X) + {\href{#1}{\color{white}{\tiny \sffamily \textbf{API}}}};} + +\newcommand{\READ}[1]{\tikz[baseline=(X.base)] + \node [fill=black!40, rectangle, inner sep=2pt,rounded corners=1pt] (X) + {\href{#1}{\color{white}{\tiny \sffamily \textbf{READ}}}};} + +\newcommand{\api}[1]{\tikz[baseline=(X.base)] + \node [fill=orange!40, rectangle, inner sep=2pt,rounded corners=1pt] (X) + {\href{#1}{\color{white}{\tiny \sffamily \textbf{API}}}};} + + +\newcommand{\plot}[5]{% + \begin{tabular}{@{}p{0.18\columnwidth}p{0.795\columnwidth}@{}} + \adjustimage{width=0.18\columnwidth,valign=t}{#1} & + {\ttfamily \scriptsize #2} \hfill \api{#3} \newline + {\scriptsize #4} \newline + {\scriptsize #5 } \vspace{.7em}\\ + \end{tabular}} + +\newcommand{\scale}[3]{% + \begin{tabular}{@{}p{0.18\columnwidth}p{0.288\columnwidth}@{}} + \adjustimage{width=0.18\columnwidth,valign=t}{#1} & {\ttfamily #2} \newline + {\scriptsize #3} + \end{tabular}} + +\newcommand{\colormap}[1]{% + \adjustimage{width=0.7\columnwidth,valign=c}{colormap-#1.pdf} & + \tiny \ttfamily #1\\ \arrayrulecolor{white}\hline +} + +\newcommand{\palette}[2]{% + \adjustimage{width=0.7\columnwidth,valign=c}{colors-#1.pdf} & + \tiny \ttfamily #2\\ \arrayrulecolor{white}\hline +} + + +\newcommand{\optional}[1]{\textcolor{gray}{#1}} +\newcommand{\mandatory}[1]{\textbf{#1}} +\newcommand{\parameter}[2]{% + \expandafter\ifstrequal\expandafter{#1}{optional}% + {\optional{#2}}{\mandatory{#2}}} +% --- Parameter: interpolation + +\newcommand{\paramx}[1]{% + \pdftooltip{\parameter{#1}{X}} + {Coordenadas horizontais de um ponto. Um escalar ou array 1D. } +} + +\newcommand{\paramy}[1]{% + \pdftooltip{\parameter{#1}{Y}}% + {Coordenadas verticais de um ponto. Um escalar ou array 1D. } +} + +\newcommand{\paramfmt}[1]{% + \pdftooltip{\parameter{#1}{fmt}}% + {Uma format string, ex. 'ro' para círculos vermelhos. Format strings são + apenas abreviações para definir propriedades básicas da linha. Tudo isso e + mais também pode ser controlado por argumentos nomeados.} +} + +\newcommand{\paramcolor}[1]{% + \pdftooltip{\parameter{#1}{color}}% + {Define a cor da linha.} +} + +\newcommand{\parammarker}[1]{% + \pdftooltip{\parameter{#1}{marker}}% + {Define estilo do marcador.} +} + +\newcommand{\paramlinestyle}[1]{% + \pdftooltip{\parameter{#1}{linestyle}}% + {Define estilo da linha.} +} + + + \newcommand{\interpolation}[1]{% + \pdftooltip{\parameter{#1}{interpolation}} + {None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', + 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', + 'bessel', 'mitchell', 'sinc', 'lanczos'} +} + +% --- Parameter: extent +\newcommand{\extent}{\pdftooltip{extent}{[left, right, bottom, top]}} + +% --- Parameter: origin +\newcommand{\origin}{\pdftooltip{origin}{'upper', 'lower'}} + +% --- Parameter: z +\newcommand{\Z}{\pdftooltip{z}{(M,N): uma imagem com dados escalares. Os valores + são mapeados para cores usando normalização e um mapa de cores.\textCR +(M, N, 3): uma imagem com valores RGB (0-1 float ou 0-255 int)\textCR +(M, N, 4): uma imagem com valores RGBA (0-1 float ou 0-255 int)}} + +% --- Parameter: cmap +\newcommand{\cmap}{\pdftooltip{cmap}{ + Uniform: 'viridis', 'plasma', 'inferno', 'magma', 'cividis'\textCR + \textCR + Sequential: 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', + 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', + 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'\textCR + \textCR + Diverging: 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', + 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', + 'seismic'\textCR + \textCR + Cyclic: 'twilight', 'twilight_shifted', 'hsv'\textCR + \textCR + Qualitative: 'Pastel1', 'Pastel2', 'Paired', 'Accent', + 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', + 'tab20', 'tab20b', 'tab20c'}} + + +\newenvironment{myboxed}[1] +{\begin{mdframed}[linecolor=black, + backgroundcolor=white, + outerlinewidth=0.25pt, + %roundcorner=0.25em, + innertopmargin=1ex, + topline=true, + rightline=true, + leftline=true, + bottomline=true, + linecolor=black!0, + frametitleaboveskip=0.5em, + frametitlebelowskip=0.5em, + innerbottommargin=.5\baselineskip, + innerrightmargin=.5em, + innerleftmargin=.5em, + %userdefinedwidth=1\textwidth, + % frametitle={\scshape \bfseries \sffamily #1}, + frametitle={\footnotesize \RobotoSlab \bfseries \hspace*{0mm} #1}, + % frametitlerule=true, + %frametitlerulecolor=red, + frametitlebackgroundcolor=black!5, + frametitlerulewidth=2pt]} +{\end{mdframed}} + + + + + +% ----------------------------------------------------------------------------- +\begin{document} +\thispagestyle{empty} +% \footnotesize +\scriptsize + +\begin{multicols*}{5} + \begin{overpic}[width=\columnwidth,tics=6,trim=12 6 18 6, clip]{logo2.png} + \put (16.5,1.5) {\scriptsize\RobotoCon \textcolor[HTML]{11557c}{Cheat sheet}} + \put (80,1.5) {\tiny\Roboto \textcolor[HTML]{11557c}{Version 3.5.0}} + \end{overpic} + %\textbf{\Large \RobotoCon Matplotlib 3.2 cheat sheet}\\ + %{\ttfamily https://matplotlib.org} \hfill CC-BY 4.0 + % \bigskip + \vspace{\fill} + %\hspace{1mm} \small \url{https://matplotlib.org/} + %\vspace{\fill} + + % --- Quick start ----------------------------------------------------------- + \begin{myboxed}{Início rápido \hfill + \API{https://matplotlib.org/tutorials/introductory/pyplot.html}} + {\ttfamily \scriptsize + import numpy as np\\ + import matplotlib as mpl\\ + import matplotlib.pyplot as plt\\ + \\ + \\ + X = np.linspace(0, 2*np.pi, 100)\\ + Y = np.cos(X)\\ + \\ + fig, ax = plt.subplots()\\ + ax.plot(X, Y, color='green')\\ + \\ + fig.savefig(``figure.pdf'')\\ + fig.show() } + \end{myboxed} + \vspace{\fill} + + % --- Figure anatomy -------------------------------------------------------- + \begin{myboxed}{Anatomia de uma figure} + \includegraphics[width=\columnwidth]{anatomy.pdf} + \end{myboxed} + \vspace{\fill} + % --- Layout --------------------------------------------------------------- + \begin{myboxed}{Layout de subplots \hfill + \API{https://matplotlib.org/tutorials/intermediate/gridspec.html} } + \plot{layout-subplot.pdf}{\textbf{subplot[s]}(rows,cols,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html} + {\ttfamily fig, axs = plt.subplots(3, 3)} + {} + \plot{layout-gridspec.pdf}{G = \textbf{gridspec}(rows,cols,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html} + {\ttfamily ax = G[0,:]}{} + \plot{layout-inset.pdf}{ax.\textbf{inset\_axes}(extent)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.inset_axes.html} + {}{} + \plot{layout-divider.pdf}{d=\textbf{make\_axes\_locatable}(ax)} + {https://matplotlib.org/mpl_toolkits/axes_grid/users/axes_divider.html} + {\ttfamily ax = d.new\_horizontal('10\%')}{} + \end{myboxed} + \vspace{\fill} + + % --- Getting help ---------------------------------------------------------- + \begin{myboxed}{Conseguindo ajuda} + \href{https://matplotlib.org} + {\faIcon{globe}\,matplotlib.org}\\ + \href{https://github.com/matplotlib/matplotlib/issues} + {\faIcon{github}\,github.com/matplotlib/matplotlib/issues}\\ + \href{https://discourse.matplotlib.org} + {\faIcon{discourse}\,discourse.matplotlib.org}\\ + \href{https://stackoverflow.com/questions/tagged/matplotlib} + {\faIcon{stack-overflow}\,stackoverflow.com/questions/tagged/matplotlib}\\ + \href{https://gitter.im/matplotlib/matplotlib} + {\faIcon{gitter}\,{https://gitter.im/matplotlib/matplotlib}}\\ + \href{https://twitter.com/matplotlib} + {\faIcon{twitter}\,twitter.com/matplotlib}\\ + \href{https://mail.python.org/mailman/listinfo/matplotlib-users} + {\faIcon[regular]{envelope}\,Matplotlib users mailing list} + \end{myboxed} + + + % --- Basic plots ----------------------------------------------------------- + \begin{myboxed}{Plots básicos} + \plot{basic-plot.pdf}{\textbf{plot}([X],Y,[fmt],…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html} + {\optional{X}, + \mandatory{Y}, + \optional{fmt}, + \optional{color}, + \optional{marker}, + \optional{linestyle}} + {} + \plot{basic-scatter.pdf}{\textbf{scatter}(X,Y,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html} + {\mandatory{X}, + \mandatory{Y}, + \optional{[s]izes}, + \optional{[c]olors}, + \optional{marker}, + \optional{cmap}} + {} + \plot{basic-bar.pdf}{\textbf{bar[h]}(x,height,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html} + { \mandatory{x}, + \mandatory{height}, + \optional{width}, + \optional{bottom}, + \optional{align}, + \optional{color} }{} + \plot{basic-imshow.pdf}{\textbf{imshow}(Z,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html} + { \mandatory{Z}, + \optional{cmap}, + \optional{interpolation}, + \optional{extent}, + \optional{origin} } + {} + \plot{basic-contour.pdf}{\textbf{contour[f]}([X],[Y],Z,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contour.html} + { \optional{X}, + \optional{Y}, + \mandatory{Z}, + \optional{levels}, + \optional{colors}, + \optional{extent}, + \optional{origin} } + {} + \plot{basic-pcolormesh.pdf}{\textbf{pcolormesh}([X],[Y],Z,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pcolormesh.html} + { \optional{X}, + \optional{Y}, + \mandatory{Z}, + \optional{vmin}, + \optional{vmax}, + \optional{cmap}} + {} + \plot{basic-quiver.pdf}{\textbf{quiver}([X],[Y],U,V,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.quiver.html} + { \optional{X}, + \optional{Y}, + \mandatory{U}, + \mandatory{V}, + \optional{C}, + \optional{units}, + \optional{angles} } + {} + \plot{basic-pie.pdf}{\textbf{pie}(X,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pie.html} + {\mandatory{Z}, + \optional{explode}, + \optional{labels}, + \optional{colors}, + \optional{radius}} + {} + \plot{basic-text.pdf}{\textbf{text}(x,y,text,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html} + {\mandatory{x}, + \mandatory{y}, + \mandatory{text}, + \optional{va}, + \optional{ha}, + \optional{size}, + \optional{weight}, + \optional{transform} } + {} + \plot{basic-fill.pdf}{\textbf{fill[\_between][x]}(…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.fill.html} + {\mandatory{X}, + \optional{Y1}, + \optional{Y2}, + \optional{color}, + \optional{where} } + {} + \end{myboxed} + \vspace{\fill} + % --- Advanced plots -------------------------------------------------------- + \begin{myboxed}{Plots avançados} + \plot{advanced-step.pdf}{\textbf{step}(X,Y,[fmt],…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.step.html} + {\mandatory{X}, + \mandatory{Y}, + \optional{fmt}, + \optional{color}, + \optional{marker}, + \optional{where} } + {} + \plot{advanced-boxplot.pdf}{\textbf{boxplot}(X,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.boxplot.html} + { \mandatory{X}, + \optional{notch}, + \optional{sym}, + \optional{bootstrap}, + \optional{widths} } + {} + \plot{advanced-errorbar.pdf}{\textbf{errorbar}(X,Y,xerr,yerr,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.errorbar.html} + { \mandatory{X}, + \mandatory{Y}, + \optional{xerr}, + \optional{yerr}, + \optional{fmt} } + {} + \plot{advanced-hist.pdf}{\textbf{hist}(X, bins, …)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html} + {\mandatory{X}, + \optional{bins}, + \optional{range}, + \optional{density}, + \optional{weights}} + {} + \plot{advanced-violin.pdf}{\textbf{violinplot}(D,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.violinplot.html} + {\mandatory{D}, + \optional{positions}, + \optional{widths}, + \optional{vert} } + {} + \plot{advanced-barbs.pdf}{\textbf{barbs}([X],[Y], U, V, …)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.barbs.html} + { \optional{X}, + \optional{Y}, + \mandatory{U}, + \mandatory{V}, + \optional{C}, + \optional{length}, + \optional{pivot}, + \optional{sizes} } + {} + \plot{advanced-event.pdf}{\textbf{eventplot}(positions,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.eventplot.html} + {\mandatory{positions}, + \optional{orientation}, + \optional{lineoffsets} } + {} + \plot{advanced-hexbin.pdf}{\textbf{hexbin}(X,Y,C,…)} + {https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hexbin.html} + {\mandatory{X}, + \mandatory{Y}, + \optional{C}, + \optional{gridsize}, + \optional{bins} } + {} + \end{myboxed} + + + % --- Scale --------------------------------------------------------------- + \begin{myboxed}{Escalas \hfill + \API{https://matplotlib.org/stable/api/scale_api.html}} + {\ttfamily ax.\textbf{set\_[xy]scale}(scale,…)} + \smallskip + \scale{scale-linear.pdf}{\textbf{linear}}{any values} + \scale{scale-log.pdf}{\textbf{log}}{values > 0} + \scale{scale-symlog.pdf}{\textbf{symlog}}{any values} + \scale{scale-logit.pdf}{\textbf{logit}}{0 < values < 1} + \end{myboxed} + % + \vspace{\fill} + % + % --- Projections ----------------------------------------------------------- + \begin{myboxed}{Projeções \hfill + \API{https://matplotlib.org/stable/api/projections_api.html}} + {\ttfamily \textbf{subplot}(…,projection=p)} + \smallskip + \scale{projection-polar.pdf}{p='polar'}{} + \scale{projection-3d.pdf} + {p='3d'\hfill\api{https://matplotlib.org/stable/api/toolkits/mplot3d.html}}{} + \plot{projection-cartopy.pdf}{p=ccrs.Orthographic()} + {https://scitools.org.uk/cartopy/docs/latest/reference/projections.html} + {import cartopy.crs as ccrs} + {} + \end{myboxed} + % + \vspace{\fill} + % + % --- Linestyles --------------------------------------------------------------- + \begin{myboxed}{Linhas \hfill + \API{https://matplotlib.org/gallery/lines_bars_and_markers/linestyles.html}} + \includegraphics[width=\columnwidth]{linestyles.pdf} + \end{myboxed} + % + \vspace{\fill} + % + % --- Markers --------------------------------------------------------------- + \begin{myboxed}{Markers \hfill + \API{https://matplotlib.org/stable/api/markers_api.html}} + \includegraphics[width=\columnwidth]{markers.pdf} + \end{myboxed} + % + \vspace{\fill} + % + % --- Colors --------------------------------------------------------------- + \begin{myboxed}{Cores \hfill + \API{https://matplotlib.org/tutorials/colors/colors.html}} + % mpl.colors.to\_rbga(\textbf{color})\smallskip\\ + \def\arraystretch{0.5} + \begin{tabular}{@{}p{0.7\columnwidth}p{0.25\columnwidth}@{}} + \palette{cycle}{'Cn'} + \palette{raw}{ 'x' } + \palette{name}{'name'} + \palette{rgba}{(R,G,B[,A])} + \palette{HexRGBA}{'\#RRGGBB[AA]'} + \palette{grey}{'x.y'} + \end{tabular} + \end{myboxed} + % + \vspace{\fill} + % + + + % --- Colormaps ------------------------------------------------------------- + \begin{myboxed}{Mapas de cores \hfill + \API{https://matplotlib.org/tutorials/colors/colormaps.html}} + {\ttfamily plt.\textbf{get\_cmap}(name) \smallskip\\} + \def\arraystretch{0.5} + \begin{tabular}{@{}p{0.7\columnwidth}p{0.25\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}Uniform & \\ + \colormap{viridis} \colormap{magma} \colormap{plasma} + % + \scriptsize \rule{0pt}{1.25em}Sequential &\\ + \colormap{Greys} \colormap{YlOrBr} \colormap{Wistia} + % + \scriptsize \rule{0pt}{1.25em}Diverging &\\ + \colormap{Spectral} \colormap{coolwarm} \colormap{RdGy} + % + \scriptsize \rule{0pt}{1.25em}Qualitative &\\ + \colormap{tab10} \colormap{tab20} + % + \scriptsize \rule{0pt}{1.25em}Cyclic &\\ + \colormap{twilight} % \colormap{hsv} + \end{tabular} + \end{myboxed} + + % --- Ticks locators -------------------------------------------------------- + \begin{myboxed}{Localizações de ticks\hfill + \API{https://matplotlib.org/stable/api/ticker_api.html}} + {\tiny \ttfamily + from matplotlib import ticker\\ + ax.[xy]axis.set\_[minor|major]\_locator(\textbf{locator})\par + \vspace{1em} + \hspace{-1em}\includegraphics[width=\columnwidth]{tick-locators.pdf} + } + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Formatadores de ticks\hfill + \API{https://matplotlib.org/stable/api/ticker_api.html}} + {\tiny \ttfamily + from matplotlib import ticker\\ + ax.[xy]axis.set\_[minor|major]\_formatter(\textbf{formatter})\par + \vspace{1em} + \hspace{-1em}\includegraphics[width=\columnwidth]{tick-formatters.pdf} + } + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Ornamentos} + {\ttfamily ax.\textbf{legend}(…) \hfill + \api{https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html}}\\ + handles, labels, loc, title, frameon\smallskip\\ + \includegraphics[width=0.9\columnwidth]{legend.pdf} + \medskip\\ + % + {\ttfamily ax.\textbf{colorbar}(…)} \hfill + \api{https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html}\\ + mappable, ax, cax, orientation \smallskip\\ + \includegraphics[width=\columnwidth]{colorbar.pdf}\\ + \medskip\\ + % + {\ttfamily ax.\textbf{annotate}(…)} \hfill + \api{https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html}\\ + \mandatory{text}, + \mandatory{xy}, + \mandatory{xytext}, + \optional{xycoords}, + \optional{textcoords}, + \optional{arrowprops} + \smallskip\\ + \includegraphics[width=\columnwidth]{annotate.pdf}\\ + % + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Event handling \hfill + \API{https://matplotlib.org/users/event_handling.html}} + {\ttfamily \scriptsize + fig, ax = plt.subplots()\par + \par + def on\_click(event):\par + ~~print(event)\par + fig.canvas.mpl\_connect(\par + ~~'button\_press\_event', on\_click)\par + } + \end{myboxed} + + % + % \vspace{\fill} + % + \begin{myboxed}{Animação \hfill + \API{https://matplotlib.org/stable/api/animation_api.html}} + {\ttfamily \scriptsize + import matplotlib.animation as mpla\par + ~\par + T = np.linspace(0, 2*np.pi, 100)\par + S = np.sin(T)\par + line, = plt.plot(T, S)\par + def animate(i):\par + ~~~~line.set\_ydata(np.sin(T+i/50))\par + anim = mpla.FuncAnimation(\par + ~~~~plt.gcf(), animate, interval=5)\par + plt.show()\par + } + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Estilos \hfill + \API{https://matplotlib.org/tutorials/introductory/customizing.html}} + \setlength{\fboxsep}{0pt}% + \setlength{\fboxrule}{.25pt}% + {\ttfamily plt.style.use(\textbf{style})\medskip}\\ + \fbox{\includegraphics[width=.32\columnwidth]{style-default.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-classic.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-grayscale.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-ggplot.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-seaborn-v0_8.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-fast.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-bmh.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-Solarize_Light2.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-seaborn-v0_8-notebook.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-default.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-classic.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-grayscale.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-ggplot.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-seaborn.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-fast.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-bmh.pdf}} + %% \fbox{\includegraphics[width=.24\columnwidth]{style-Solarize_Light2.pdf}} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Lembrete rápido} + {\ttfamily + ax.\textbf{grid}()\\ + ax.\textbf{set\_[xy]lim}(vmin, vmax)\\ + ax.\textbf{set\_[xy]label}(label)\\ + ax.\textbf{set\_[xy]ticks}(ticks, [labels])\\ + ax.\textbf{set\_[xy]ticklabels}(labels)\\ + ax.\textbf{set\_title}(title)\\ + ax.\textbf{tick\_params}(width=10, …)\\ + ax.\textbf{set\_axis\_[on|off]}()\\ + \\ + fig.\textbf{suptitle}(title)\\ + fig.\textbf{tight\_layout}()\\ + plt.\textbf{gcf}(), plt.\textbf{gca}()\\ + mpl.\textbf{rc}('axes', linewidth=1, …)\\ + {[fig|ax]}.patch.\textbf{set\_alpha}(0)\\ + \verb|text=r'$\frac{-e^{i\pi}}{2^n}$'|} + \end{myboxed} + % + \vspace{\fill} + % + %% % --- Toolkits -------------------------------------------------------------- + %% \begin{myboxed}{Toolkits and libraries} + %% \href{https://matplotlib.org/basemap/}{Basemap} --- + %% \href{https://scitools.org.uk/cartopy/docs/latest/}{Cartopy} --- + %% \href{https://geopandas.org/}{GeoPandas} --- + %% \href{https://residentmario.github.io/geoplot/index.html}{Geoplot} --- + %% \href{https://github.com/yhat/ggpy}{GGPlot} --- + %% \href{http://holoviews.org/}{Holoviews} --- + %% \href{https://seaborn.pydata.org/}{Seaborn} --- + %% \href{https://gr-framework.org/}{GR Framework} --- + %% \href{https://www.scikit-yb.org/en/latest/}{Yellowbrick} + %% \end{myboxed} + %% % + %% \vspace{\fill} + % + \begin{myboxed}{Atalhos de teclado\hfill + \API{https://matplotlib.org/users/navigation_toolbar.html}} + \def\arraystretch{1.25} + \begin{tabular}{ll} + \keys{\ctrl+s} Save & \keys{\ctrl+w} Close plot\\ + \keys{r} Reset view & \keys{f} Fullscreen 0/1\\ + \keys{f} View forward & \keys{b} View back\\ + \keys{p} Pan view & \keys{o} Zoom to rect\\ + \keys{x} X pan/zoom & \keys{y} Y pan/zoom\\ + \keys{g} Minor grid 0/1 & \keys{G} Major grid 0/1\\ + \keys{l} X axis log/linear & \keys{L} Y axis log/linear\\ + %\keys{l} & Toggle y linear / log axis\\ + \end{tabular} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Dez regras simples\hfill + \READ{https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003833}} + 1. Conheça sua audiência\\ + 2. Identifique sua mensagem\\ + 3. Adapte a figura\\ + 4. Legendas não são opcionais\\ + 5. Não confie nos defaults\\ + 6. Use cores efetivamente\\ + 7. Não confunda o leitor\\ + 8. Evite “chartjunk”\\ + 9. Messagem supera beleza\\ + 10. Tenha a ferramenta correta + \end{myboxed} +\end{multicols*} + +\begin{multicols*}{5} + \begin{myboxed}{Ajustes nos eixos\hfill + \API{https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots_adjust.html}} + plt.\textbf{subplots\_adjust}( … )\\ + + \includegraphics[width=\columnwidth]{adjustments.pdf} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Extent \& origin \hfill + \API{https://matplotlib.org/tutorials/intermediate/imshow_extent.html} } + ax.\textbf{imshow}( extent=…, origin=… )\\ + + \includegraphics[width=\columnwidth]{extents.pdf} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Alinhamento de texto\hfill + \API{https://matplotlib.org/tutorials/text/text_props.html} } + ax.\textbf{text}( …, ha=… , va=…, …)\\ + + \includegraphics[width=\columnwidth]{text-alignments.pdf} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Parâmetros de texto \hfill + \API{https://matplotlib.org/tutorials/text/text_props.html}} + ax.\textbf{text}(…, family=…, size=…, weight=…)\\ + ax.\textbf{text}(…, fontproperties=…)\\ + + \includegraphics[width=\columnwidth]{fonts.pdf} + \end{myboxed} + + + \begin{myboxed}{Mapas de cor uniforme} + \begin{tabular}{@{}p{0.7\columnwidth}p{0.25\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}\noindent + \colormap{viridis} + \colormap{plasma} + \colormap{inferno} + \colormap{magma} + \colormap{cividis} + \end{tabular} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Mapas de cor sequenciais} + \begin{tabular}{@{}p{0.7\columnwidth}p{0.25\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}\noindent + \colormap{Greys} + \colormap{Purples} + \colormap{Blues} + \colormap{Greens} + \colormap{Oranges} + \colormap{Reds} + \colormap{YlOrBr} + \colormap{YlOrRd} + \colormap{OrRd} + \colormap{PuRd} + \colormap{RdPu} + \colormap{BuPu} + \colormap{GnBu} + \colormap{PuBu} + \colormap{YlGnBu} + \colormap{PuBuGn} + \colormap{BuGn} + \colormap{YlGn} + \end{tabular} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Mapas de cores divergentes} + \begin{tabular}{@{}p{0.7\columnwidth}p{0.25\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}\noindent + \colormap{PiYG} + \colormap{PRGn} + \colormap{BrBG} + \colormap{PuOr} + \colormap{RdGy} + \colormap{RdBu} + \colormap{RdYlBu} + \colormap{RdYlGn} + \colormap{Spectral} + \colormap{coolwarm} + \colormap{bwr} + \colormap{seismic} + \end{tabular} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Mapas de cores qualitativos} + \begin{tabular}{@{}p{0.7\columnwidth}p{0.25\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}\noindent + \colormap{Pastel1} + \colormap{Pastel2} + \colormap{Paired} + \colormap{Accent} + \colormap{Dark2} + \colormap{Set1} + \colormap{Set2} + \colormap{Set3} + \colormap{tab10} + \colormap{tab20} + \colormap{tab20b} + \colormap{tab20c} + \end{tabular} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Mapas de cores diversos} + \begin{tabular}{@{}p{0.7\columnwidth}p{0.25\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}\noindent + \colormap{terrain} + \colormap{ocean} + \colormap{cubehelix} + \colormap{rainbow} + \colormap{twilight} + \end{tabular} + \end{myboxed} + + + + \begin{myboxed}{Nomes de cores \hfill + \API{https://matplotlib.org/stable/api/colors_api.html} } + \includegraphics[width=\columnwidth]{colornames.pdf} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Interpolação de image + \hfill \API{https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html} } + \smallskip +%% plt.\textbf{imshow}(…, interpolation=…)\\ +%% plt.\textbf{contour[f]}(…, interpolation=…)\\ + \includegraphics[width=\columnwidth]{interpolations.pdf} + \end{myboxed} + + + \begin{myboxed}{Localização da legenda} + \includegraphics[width=\columnwidth]{legend-placement.pdf} + ax.\textbf{legend}(loc="string", bbox\_to\_anchor=(x,y))\\ + \begin{tabular}{@{}p{0.33\columnwidth} + p{0.33\columnwidth} + p{0.33\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}\noindent + 2: upper left & 9: upper center & 1: upper right\\ + 6: center left & 10: center & 7: center right\\ + 3: lower left & 8: lower center & 4: lower right\\ + \end{tabular} + + \begin{tabular}{@{}p{0.495\columnwidth} + p{0.495\columnwidth}@{}} + \scriptsize \rule{0pt}{1.25em}\noindent + \tiny A: upper right / {\ttfamily (-0.1,0.9)} & \tiny B: center right / {\ttfamily (-0.1,0.5)}\\ + \tiny C: lower right / {\ttfamily (-0.1,0.1)} & \tiny D: upper left / {\ttfamily (0.1,-0.1)}\\ + \tiny E: upper center / {\ttfamily (0.5,-0.1)} & \tiny F: upper right / {\ttfamily (0.9,-0.1)}\\ + \tiny G: lower left / {\ttfamily (1.1,0.1)} & \tiny H: center left / {\ttfamily (1.1,0.5)}\\ + \tiny I: upper left / {\ttfamily (1.1,0.9)} & \tiny J: lower right / {\ttfamily (0.9,1.1)}\\ + \tiny K: lower center / {\ttfamily (0.5,1.1)} & \tiny L: lower left / {\ttfamily (0.1,1.1)} + \end{tabular} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Estilo de anotação de conexões \hfill + \API{https://matplotlib.org/tutorials/text/annotations.html} } + \includegraphics[width=\columnwidth]{annotation-connection-styles.pdf} + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Estilo de anotações de setas\hfill + \API{https://matplotlib.org/tutorials/text/annotations.html} } + \includegraphics[width=\columnwidth]{annotation-arrow-styles.pdf} + \end{myboxed} + + % + \vspace{\fill} + % + + % + \begin{myboxed}{Como eu …} + \textbf{… redimensiono uma figura?}\\ + \hspace*{2.5mm}~$\rightarrow$ fig.set\_size\_inches(w, h)\\ + \textbf{… salvo uma figura?}\\ + \hspace*{2.5mm}~$\rightarrow$ fig.savefig("figure.pdf")\\ + \textbf{… salve uma figura transparente?}\\ + \hspace*{2.5mm}~$\rightarrow$ fig.savefig("figure.pdf", transparent=True)\\ + \textbf{… limpo uma figura/um eixo?}\\ + \hspace*{2.5mm}~$\rightarrow$ fig.clear() $\rightarrow$ ax.clear()\\ + \textbf{… fecho todas as figuras?}\\ + \hspace*{2.5mm}~$\rightarrow$ plt.close("all")\\ + \textbf{… removo ticks?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.set\_[xy]ticks([])\\ + \textbf{… removo rótulos de ticks?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.set\_[xy]ticklabels([])\\ + \textbf{… rotaciono rótulos de ticks?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.tick\_params(axis="x", rotation=90)\\ + \textbf{… escondo top spine?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.spines['top'].set\_visible(False)\\ + \textbf{… escondo borda da legenda?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.legend(frameon=False)\\ + \textbf{… mostro erro como uma região sombreada?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.fill\_between(X, Y+error, Y-error)\\ + \textbf{… desenho um retângulo?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.add\_patch(plt.Rectangle((0, 0), 1, 1)\\ + \textbf{… desenho uma linha vertical?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.axvline(x=0.5)\\ + \textbf{… desenho fora do frame?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.plot(…, clip\_on=False)\\ + \textbf{… uso transparência?}\\ + \hspace*{2.5mm}~$\rightarrow$ ax.plot(…, alpha=0.25)\\ + \textbf{… converto uma imagem RGB em uma imagem cinza? }\\ + \hspace*{2.5mm}~$\rightarrow$ gray = 0.2989*R + 0.5870*G + 0.1140*B\\ + \textbf{… defino uma cor de fundo para a figura?}\\ + \hspace*{2.5mm}~$\rightarrow$ fig.patch.set\_facecolor(``grey'')\\ + \textbf{… obtenho um mapa de cor reverso?}\\ + \hspace*{2.5mm}~$\rightarrow$ plt.get\_cmap(``viridis\_r'')\\ + \textbf{… obtenho um mapa de cor discreto?}\\ + \hspace*{2.5mm}~$\rightarrow$ plt.get\_cmap(``viridis'', 10)\\ + \textbf{… mostro uma figura por um segundo?}\\ + \hspace*{2.5mm}~$\rightarrow$ fig.show(block=False), time.sleep(1) + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Dicas de performance} + \smallskip + {\ttfamily \fontsize{6pt}{7pt}\selectfont + % + \textcolor{red}{scatter(X, Y) \hfill devagar}\\ + plot(X, Y, marker="o", ls="") \hfill rápido% + \vskip.5\baselineskip + % + \textcolor{red}{for i in range(n): plot(X[i]) \hfill devagar}\\ + plot(sum([x+[None] for x in X],[])) \hfill rápido% + \vskip.5\baselineskip + % + \textcolor{red}{cla(), imshow(…), canvas.draw() \hfill devagar}\\ + im.set\_data(…), canvas.draw() \hfill rápido% + \vskip.1\baselineskip + } + \end{myboxed} + % + \vspace{\fill} + % + \begin{myboxed}{Além do Matplotlib} + \smallskip + \href{https://seaborn.pydata.org/}{\textbf{Seaborn}}: Visualização de dado estatísticos\\ + \href{https://scitools.org.uk/cartopy/docs/latest/}{\textbf{Cartopy}}: Processamento de dados geoespaciais\\ + \href{https://yt-project.org/doc/index.html}{\textbf{yt}}: Visualização de dados volumétricos\\ + \href{https://mpld3.github.io}{\textbf{mpld3}}: Trazendo Matplotlib para o navegador\\ + \href{https://datashader.org/}{\textbf{Datashader}}: Large data processing pipeline\\ + \href{https://plotnine.readthedocs.io/en/latest/}{\textbf{plotnine}}: Uma gramática de gráficos para Python + \end{myboxed} + % + \begin{center} + \href{https://github.com/matplotlib/cheatsheets}{Matplotlib Cheatsheets}\\ + Copyright (c) 2021 Matplotlib Development Team\\ + Released under a CC-BY 4.0 International License\\ + \smallskip + \includegraphics[width=\columnwidth]{numfocus.png} + \end{center} + +\end{multicols*} +\end{document} diff --git a/cheatsheets.tex b/cheatsheets.tex index 09c86a1..81b7303 100644 --- a/cheatsheets.tex +++ b/cheatsheets.tex @@ -682,11 +682,11 @@ \fbox{\includegraphics[width=.32\columnwidth]{style-classic.pdf}} \fbox{\includegraphics[width=.32\columnwidth]{style-grayscale.pdf}} \fbox{\includegraphics[width=.32\columnwidth]{style-ggplot.pdf}} - \fbox{\includegraphics[width=.32\columnwidth]{style-seaborn.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-seaborn-v0_8.pdf}} \fbox{\includegraphics[width=.32\columnwidth]{style-fast.pdf}} \fbox{\includegraphics[width=.32\columnwidth]{style-bmh.pdf}} \fbox{\includegraphics[width=.32\columnwidth]{style-Solarize_Light2.pdf}} - \fbox{\includegraphics[width=.32\columnwidth]{style-seaborn-notebook.pdf}} + \fbox{\includegraphics[width=.32\columnwidth]{style-seaborn-v0_8-notebook.pdf}} %% \fbox{\includegraphics[width=.24\columnwidth]{style-default.pdf}} %% \fbox{\includegraphics[width=.24\columnwidth]{style-classic.pdf}} %% \fbox{\includegraphics[width=.24\columnwidth]{style-grayscale.pdf}} diff --git a/handout-beginner.pt-br.tex b/handout-beginner.pt-br.tex new file mode 100644 index 0000000..a03e5e0 --- /dev/null +++ b/handout-beginner.pt-br.tex @@ -0,0 +1,307 @@ +\documentclass[10pt,landscape,a4paper]{article} +\usepackage[right=10mm, left=10mm, top=10mm, bottom=10mm]{geometry} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage[english]{babel} +\usepackage[rm,light]{roboto} +\usepackage{xcolor} +\usepackage{graphicx} +\graphicspath{{./figures/}} +\usepackage{multicol} +\usepackage{colortbl} +\usepackage{array} +\setlength\parindent{0pt} +\setlength{\tabcolsep}{2pt} +\baselineskip=0pt +\setlength\columnsep{1em} +\definecolor{Gray}{gray}{0.85} + +% --- Listing ----------------------------------------------------------------- +\usepackage{listings} +\lstset{ + frame=tb, framesep=4pt, framerule=0pt, + backgroundcolor=\color{black!5}, + basicstyle=\ttfamily, + commentstyle=\ttfamily\color{black!50}, + breakatwhitespace=false, + breaklines=true, + extendedchars=true, + keepspaces=true, + language=Python, + rulecolor=\color{black}, + showspaces=false, + showstringspaces=false, + showtabs=false, + tabsize=2, + % + emph = { plot, scatter, imshow, bar, contourf, pie, subplots, show, savefig, + errorbar, boxplot, hist, set_title, set_xlabel, set_ylabel, suptitle, }, + emphstyle = {\ttfamily\bfseries} +} + +% --- Fonts ------------------------------------------------------------------- +\usepackage{fontspec} +\usepackage[babel=true]{microtype} +\defaultfontfeatures{Ligatures = TeX, Mapping = tex-text} +\setsansfont{Roboto} [ Path = fonts/roboto/Roboto-, + Extension = .ttf, + UprightFont = Light, + ItalicFont = LightItalic, + BoldFont = Regular, + BoldItalicFont = Italic ] +\setromanfont{RobotoSlab} [ Path = fonts/roboto-slab/RobotoSlab-, + Extension = .ttf, + UprightFont = Light, + BoldFont = Bold ] +\setmonofont{RobotoMono} [ Path = fonts/roboto-mono/RobotoMono-, + Extension = .ttf, + Scale = 0.90, + UprightFont = Light, + ItalicFont = LightItalic, + BoldFont = Regular, + BoldItalicFont = Italic ] +\renewcommand{\familydefault}{\sfdefault} + +% ----------------------------------------------------------------------------- +\begin{document} +\thispagestyle{empty} + +\section*{\LARGE \rmfamily + Matplotlib \textcolor{orange}{\mdseries para iniciantes}} + +\begin{multicols*}{3} + +Matplotlib é uma biblioteca para gerar plots em 2D e 3D em Python. Foi criada +com a filosofia de que você deve ser capaz de criar plots simples com apenas +alguns comandos:\\ + +\fbox{1} \textbf{Inicialize} +\begin{lstlisting} + import numpy as np + import matplotlib.pyplot as plt +\end{lstlisting} +% +\fbox{2} \textbf{Prepare} +\begin{lstlisting} + X = np.linspace(0, 4*np.pi, 1000) + Y = np.sin(X) +\end{lstlisting} +% +\fbox{3} \textbf{Renderize} +\begin{lstlisting} + fig, ax = plt.subplots() + ax.plot(X, Y) + fig.show() +\end{lstlisting} +% +\fbox{4} \textbf{Observe} \medskip\\ +\includegraphics[width=\linewidth]{sine.pdf} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Escolha} +% ----------------------------------------------------------------------------- + +Matplotlib oferece diversos tipos de plots (veja Galeria): \medskip + +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.random.uniform(0, 1, 100) + Y = np.random.uniform(0, 1, 100) + ax.scatter(X, Y) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{basic-scatter.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.arange(10) + Y = np.random.uniform(1, 10, 10) + ax.bar(X, Y) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{basic-bar.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + Z = np.random.uniform(0, 1, (8,8)) + + ax.imshow(Z) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{basic-imshow.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + Z = np.random.uniform(0, 1, (8,8)) + + ax.contourf(Z) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{basic-contour.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + Z = np.random.uniform(0, 1, 4) + + ax.pie(Z) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{basic-pie.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + Z = np.random.normal(0, 1, 100) + + ax.hist(Z) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{advanced-hist.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.arange(5) + Y = np.random.uniform(0, 1, 5) + ax.errorbar(X, Y, Y/4) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{advanced-errorbar.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + Z = np.random.normal(0, 1, (100,3)) + + ax.boxplot(Z) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{advanced-boxplot.pdf}} +\end{tabular} + + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Modifique} +% ----------------------------------------------------------------------------- +Você pode modificar praticamente tudo em um plot, incluindo limites, +cores, marcadores, grossura e estilo de linhas, ticks e rótulos de ticks, +títulos, etc. \medskip + +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.linspace(0, 10, 100) + Y = np.sin(X) + ax.plot(X, Y, color="black") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-color.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.linspace(0, 10, 100) + Y = np.sin(X) + ax.plot(X, Y, linestyle="--") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-linestyle.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.linspace(0, 10, 100) + Y = np.sin(X) + ax.plot(X, Y, linewidth=5) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-linewidth.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.linspace(0, 10, 100) + Y = np.sin(X) + ax.plot(X, Y, marker="o") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-marker.pdf}} +\end{tabular} + + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Organize} +% ----------------------------------------------------------------------------- + +Você pode plotar diferentes dados na mesma figura, mas você também +pode dividir uma figura em diversos subplots (chamados {\em Axes}): \medskip + +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.linspace(0, 10, 100) + Y1, Y2 = np.sin(X), np.cos(X) + ax.plot(X, Y1, X, Y2) +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-multi.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + fig, (ax1, ax2) = plt.subplots(2,1) + ax1.plot(X, Y1, color="C1") + ax2.plot(X, Y2, color="C0") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-vsplit.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + fig, (ax1, ax2) = plt.subplots(1,2) + ax1.plot(Y1, X, color="C1") + ax2.plot(Y2, X, color="C0") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-hsplit.pdf}} +\end{tabular} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Rotule \mdseries (tudo)} +% ----------------------------------------------------------------------------- +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + ax.plot(X, Y) + fig.suptitle(None) + ax.set_title("Uma senoide") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-title.pdf}} +\end{tabular} +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + ax.plot(X, Y) + ax.set_ylabel(None) + ax.set_xlabel("Tempo") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{plot-xlabel.pdf}} +\end{tabular} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Explore} +% ----------------------------------------------------------------------------- + +As figuras estão contidas em uma interface gráfica que permite manipulações como modificar o zoom +e deslocar a figura, navegar entre diferentes visualizações e +mostrar o valor selecionado pelo mouse. + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Salve \mdseries (bitmap ou vetor)} +% ----------------------------------------------------------------------------- +\begin{lstlisting}[belowskip=-\baselineskip] + fig.savefig("minha-primeira-figura.png", dpi=300) + fig.savefig("minha-primeira-figura.pdf") +\end{lstlisting} +% +\vfill +% +{\scriptsize + Matplotlib 3.5.0 handout for beginners. + Copyright (c) 2021 Matplotlib Development Team. + Released under a CC-BY 4.0 International License. + Supported by NumFOCUS. +\par} + +\end{multicols*} +\end{document} diff --git a/handout-beginner.tex b/handout-beginner.tex index 690a844..a4008a6 100644 --- a/handout-beginner.tex +++ b/handout-beginner.tex @@ -71,7 +71,7 @@ \section*{\LARGE \rmfamily \begin{multicols*}{3} -Matplotlib is a library for making 2D plots in Python. It is designed +Matplotlib is a library for making 2D and 3D plots in Python. It is designed with the philosophy that you should be able to create simple plots with just a few commands:\\ diff --git a/handout-intermediate.pt-br.tex b/handout-intermediate.pt-br.tex new file mode 100644 index 0000000..6842d33 --- /dev/null +++ b/handout-intermediate.pt-br.tex @@ -0,0 +1,210 @@ +\documentclass[10pt,landscape,a4paper]{article} +\usepackage[right=10mm, left=10mm, top=10mm, bottom=10mm]{geometry} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage[english]{babel} +\usepackage[rm,light]{roboto} +\usepackage{xcolor} +\usepackage{graphicx} +\graphicspath{{./figures/}} +\usepackage{multicol} +\usepackage{colortbl} +\usepackage{array} +\setlength\parindent{0pt} +\setlength{\tabcolsep}{2pt} +\baselineskip=0pt +\setlength\columnsep{1em} +\definecolor{Gray}{gray}{0.85} + +% --- Listing ----------------------------------------------------------------- +\usepackage{listings} +\lstset{ + frame=tb, framesep=4pt, framerule=0pt, + backgroundcolor=\color{black!5}, + basicstyle=\ttfamily, + commentstyle=\ttfamily\color{black!50}, + breakatwhitespace=false, + breaklines=true, + extendedchars=true, + keepspaces=true, + language=Python, + rulecolor=\color{black}, + showspaces=false, + showstringspaces=false, + showtabs=false, + tabsize=2, + % + emph = { plot, scatter, imshow, bar, contourf, pie, subplots, spines, + add_gridspec, add_subplot, set_xscale, set_minor_locator, + annotate, set_minor_formatter, tick_params, fill_betweenx, text, legend, + errorbar, boxplot, hist, title, xlabel, ylabel, suptitle }, + emphstyle = {\ttfamily\bfseries} +} + +% --- Fonts ------------------------------------------------------------------- +\usepackage{fontspec} +\usepackage[babel=true]{microtype} +\defaultfontfeatures{Ligatures = TeX, Mapping = tex-text} +\setsansfont{Roboto} [ Path = fonts/roboto/Roboto-, + Extension = .ttf, + UprightFont = Light, + ItalicFont = LightItalic, + BoldFont = Regular, + BoldItalicFont = Italic ] +\setromanfont{RobotoSlab} [ Path = fonts/roboto-slab/RobotoSlab-, + Extension = .ttf, + UprightFont = Light, + BoldFont = Bold ] +\setmonofont{RobotoMono} [ Path = fonts/roboto-mono/RobotoMono-, + Extension = .ttf, + Scale = 0.90, + UprightFont = Light, + ItalicFont = LightItalic, + BoldFont = Regular, + BoldItalicFont = Italic ] +\renewcommand{\familydefault}{\sfdefault} + +% ----------------------------------------------------------------------------- +\begin{document} +\thispagestyle{empty} + +\section*{\LARGE \rmfamily + Matplotlib \textcolor{orange}{\mdseries para utilizadores de nível intermediário}} + +\begin{multicols*}{3} + +Uma figura matplotlib é composta por uma hierarquia de elementos que formam +a figura atual. Cada elemento pode ser modificado. \medskip + +\includegraphics[width=\linewidth]{anatomy.pdf} + +\subsection*{\rmfamily Figure, axes \& spines} + +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + fig, axs = plt.subplots(3,3) + axs[0,0].set_facecolor("#ddddff") + axs[2,2].set_facecolor("#ffffdd") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{layout-subplot-color.pdf}} +\end{tabular} + +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + gs = fig.add_gridspec(3, 3) + ax = fig.add_subplot(gs[0, :]) + ax.set_facecolor("#ddddff") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{layout-gridspec-color.pdf}} +\end{tabular} + +% ----------------------------------------------------------------------------- +\begin{tabular}{@{}m{.821\linewidth}m{.169\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + fig, ax = plt.subplots() + ax.spines["top"].set_color("None") + ax.spines["right"].set_color("None") +\end{lstlisting} +& \raisebox{-0.75em}{\includegraphics[width=\linewidth]{layout-spines.pdf}} +\end{tabular} + + + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Ticks \& rótulos} + +\begin{lstlisting}[basicstyle=\ttfamily\small] + from mpl.ticker import MultipleLocator as ML + from mpl.ticker import ScalarFormatter as SF + ax.xaxis.set_minor_locator(ML(0.2)) + ax.xaxis.set_minor_formatter(SF()) + ax.tick_params(axis='x',which='minor',rotation=90) +\end{lstlisting} +\includegraphics[width=\linewidth]{tick-multiple-locator.pdf} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Linhas \& marcadores} + +\begin{lstlisting} + X = np.linspace(0.1, 10*np.pi, 1000) + Y = np.sin(X) + ax.plot(X, Y, "C1o:", markevery=25, mec="1.0") +\end{lstlisting} +\includegraphics[width=\linewidth]{sine-marker.pdf} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Escalas \& projeções} + +\begin{lstlisting} + fig, ax = plt.subplots() + ax.set_xscale("log") + ax.plot(X, Y, "C1o-", markevery=25, mec="1.0") +\end{lstlisting} +\includegraphics[width=\linewidth]{sine-logscale.pdf} + +\subsection*{\rmfamily Texto \& ornamentos} +\begin{lstlisting}[] + ax.fill_betweenx([-1,1],[0],[2*np.pi]) + ax.text(0, -1, r" Period $\Phi$") +\end{lstlisting} +\includegraphics[width=\linewidth]{sine-period.pdf} + + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Legenda} +\begin{lstlisting}[] + ax.plot(X, np.sin(X), "C0", label="Sine") + ax.plot(X, np.cos(X), "C1", label="Cosine") + ax.legend(bbox_to_anchor=(0,1,1,.1),ncol=2, + mode="expand", loc="lower left") +\end{lstlisting} +\includegraphics[width=\linewidth]{sine-legend.pdf} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Anotação} +\begin{lstlisting}[] + ax.annotate("A", (X[250],Y[250]),(X[250],-1), + ha="center", va="center",arrowprops = + {"arrowstyle" : "->", "color": "C1"}) +\end{lstlisting} +\includegraphics[width=\linewidth]{sine-annotate.pdf} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Cores} + +Qualquer cor pode ser usada, mas o Matplotlib oferece um conjunto de cores:\\ +\includegraphics[width=\linewidth]{colors-cycle.pdf} \smallskip +\includegraphics[width=\linewidth]{colors-grey.pdf}\\ +%As well as nice colormaps (viridis an magma):\\ +%\includegraphics[width=\linewidth]{colormap-viridis.pdf} \smallskip +%\includegraphics[width=\linewidth]{colormap-magma.pdf} \medskip + +% ----------------------------------------------------------------------------- +\vspace{-1em} +\subsection*{\rmfamily Tamanho \& DPI} + +Considere uma figura quadradada a ser incluída em uma folha de papel A4 de duas colunas com +margem de 2cm em cada lado e uma coluna de separação de 1cm. A largura de um figura é +(21 - 2*2 - 1)/2 = 8cm. Uma polegada sendo 2.54cm, tamanho da figura deve ser +3.15$\times$3.15 in. +\begin{lstlisting}[] + fig = plt.figure(figsize=(3.15,3.15), dpi=50) + plt.savefig("figure.pdf", dpi=600) +\end{lstlisting} + + +\vfill +% +{\scriptsize + Matplotlib 3.5.0 handout for intermediate users. + Copyright (c) 2021 Matplotlib Development Team. + Released under a CC-BY 4.0 International License. + Supported by NumFOCUS. +\par} + + + +\end{multicols*} +\end{document} diff --git a/handout-tips.pt-br.tex b/handout-tips.pt-br.tex new file mode 100644 index 0000000..c263d96 --- /dev/null +++ b/handout-tips.pt-br.tex @@ -0,0 +1,257 @@ +\documentclass[10pt,landscape,a4paper]{article} +\usepackage[right=10mm, left=10mm, top=10mm, bottom=10mm]{geometry} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage[english]{babel} +\usepackage[rm,light]{roboto} +\usepackage{xcolor} +\usepackage{graphicx} +\graphicspath{{./figures/}} +\usepackage{multicol} +\usepackage{colortbl} +\usepackage{array} +\setlength\parindent{0pt} +\setlength{\tabcolsep}{2pt} +\baselineskip=0pt +\setlength\columnsep{1em} +\definecolor{Gray}{gray}{0.85} + +% --- Listing ----------------------------------------------------------------- +\usepackage{listings} +\lstset{ + frame=tb, framesep=4pt, framerule=0pt, + backgroundcolor=\color{black!5}, + basicstyle=\ttfamily\footnotesize, + commentstyle=\ttfamily\color{black!50}, + breakatwhitespace=false, + breaklines=true, + extendedchars=true, + keepspaces=true, + language=Python, + rulecolor=\color{black}, + showspaces=false, + showstringspaces=false, + showtabs=false, + tabsize=2, + % + emph = { + plot, scatter, imshow, bar, contourf, pie, subplots, spines, + add_gridspec, add_subplot, set_xscale, set_minor_locator, linestyle, + dash_capstyle, projection, Stroke, Normal, add_axes, label, savefig, + get_cmap, histtype, annotate, set_minor_formatter, tick_params, + fill_betweenx, text, legend, errorbar, boxplot, hist, title, xlabel, + ylabel, suptitle, fraction, pad, set_fontname, get_xticklabels}, + emphstyle = {\ttfamily\bfseries} +} + +% --- Fonts ------------------------------------------------------------------- +\usepackage{fontspec} +\usepackage[babel=true]{microtype} +\defaultfontfeatures{Ligatures = TeX, Mapping = tex-text} +\setsansfont{Roboto} [ Path = fonts/roboto/Roboto-, + Extension = .ttf, + UprightFont = Light, + ItalicFont = LightItalic, + BoldFont = Regular, + BoldItalicFont = Italic ] +\setromanfont{RobotoSlab} [ Path = fonts/roboto-slab/RobotoSlab-, + Extension = .ttf, + UprightFont = Light, + BoldFont = Bold ] +\setmonofont{RobotoMono} [ Path = fonts/roboto-mono/RobotoMono-, + Extension = .ttf, + Scale = 0.90, + UprightFont = Light, + ItalicFont = LightItalic, + BoldFont = Regular, + BoldItalicFont = Italic ] +\renewcommand{\familydefault}{\sfdefault} + +% ----------------------------------------------------------------------------- +\begin{document} +\thispagestyle{empty} + +\section*{\LARGE \rmfamily + Matplotlib \textcolor{orange}{\mdseries dicas \& truques}} + +\begin{multicols*}{3} + + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Transparência} + +Gráficos de dispersão podem ser melhorados ao usar a transparência (alpha) para +mostrar uma área com maior densidade. Múltiplos gráficos de dispersão podem ser +usados para delinear uma fronteira. + +\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.random.normal(-1, 1, 500) + Y = np.random.normal(-1, 1, 500) + ax.scatter(X, Y, 50, "0.0", lw=2) # optional + ax.scatter(X, Y, 50, "1.0", lw=0) # optional + ax.scatter(X, Y, 40, "C1", lw=0, alpha=0.1) +\end{lstlisting} & +\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-transparency.pdf}} +\end{tabular} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Rasterização} +Se a sua figura tem muitos elementos gráficos, como um gráfico de dispersão +gigante, você pode rasterizá-los para salvar memória e manter outros elementos +em formato vetorial. +\begin{lstlisting} + X = np.random.normal(-1, 1, 10_000) + Y = np.random.normal(-1, 1, 10_000) + ax.scatter(X, Y, rasterized=True) + fig.savefig("rasterized-figure.pdf", dpi=600) +\end{lstlisting} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Renderização offline} + +Use o backend Agg para renderizar a figura diretamente em um array. +\begin{lstlisting} + from matplotlib.backends.backend_agg import FigureCanvas + canvas = FigureCanvas(Figure())) + ... # draw some stuff + canvas.draw() + Z = np.array(canvas.renderer.buffer_rgba()) +\end{lstlisting} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Faixa contínua de cores} + +Você pode usar um mapa de cor (colormap) para escolher de uma faixa de cores +contínuas. + +\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + X = np.random.randn(1000, 4) + cmap = plt.get_cmap("Oranges") + colors = cmap([0.2, 0.4, 0.6, 0.8]) + + ax.hist(X, 2, histtype='bar', color=colors) +\end{lstlisting} & +\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-color-range.pdf}} +\end{tabular} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Contorno de texto} +Use o contorno de texto para deixar o texto mais visível. + +\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + import matplotlib.patheffects as fx + text = ax.text(0.5, 0.1, "Label") + text.set_path_effects([ + fx.Stroke(linewidth=3, foreground='1.0'), + fx.Normal()]) +\end{lstlisting} & +\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-outline.pdf}} +\end{tabular} + + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Plot multilinhas} +Você pode plotar várias linhas ao mesmo tempo usando None como separador. + +\begin{lstlisting} + X,Y = [], [] + for x in np.linspace(0, 10*np.pi, 100): + X.extend([x, x, None]), Y.extend([0, sin(x), None]) + ax.plot(X, Y, "black") +\end{lstlisting} +\includegraphics[width=\linewidth]{tip-multiline.pdf} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Linhas pontilhadas} +Para obter linhas pontilhadas arredondadas, use o {\ttfamily linestyle} +customizado e modifique o {\ttfamily dash\_capstyle}. +\begin{lstlisting} + ax.plot([0,1], [0,0], "C1", + linestyle = (0, (0.01, 1)), dash_capstyle="round") + ax.plot([0,1], [1,1], "C1", + linestyle = (0, (0.01, 2)), dash_capstyle="round") +\end{lstlisting} +\includegraphics[width=\linewidth]{tip-dotted.pdf} + +% ----------------------------------------------------------------------------- +\subsection*{\rmfamily Eixos combinados} +Você pode usar eixos sobrepostos com diferentes projeções. + +\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + ax1 = fig.add_axes([0,0,1,1], + label="cartesian") + ax2 = fig.add_axes([0,0,1,1], + label="polar", + projection="polar") +\end{lstlisting} & +\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-dual-axis.pdf}} +\end{tabular} + +\subsection*{\rmfamily Ajuste da barra de cores} +Você consegue ajustar o tamanho de uma barra de cores (colorbar) quando a +adiciona. + +\begin{tabular}{@{}m{.754\linewidth}m{.236\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + im = ax.imshow(Z) + + cb = plt.colorbar(im, + fraction=0.046, pad=0.04) + cb.set_ticks([]) +\end{lstlisting} & +\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-colorbar.pdf}} +\end{tabular} + +\subsection*{\rmfamily Tirando vantagem da tipografia} +Você pode usar uma fonte condensada como a Roboto Condensed para salvar espaço +nos rótulos dos ticks. + +\begin{lstlisting} + for tick in ax.get_xticklabels(which='both'): + tick.set_fontname("Roboto Condensed") +\end{lstlisting} +\includegraphics[width=\linewidth]{tip-font-family.pdf} + +\subsection*{\rmfamily Se livrando das margens} +Uma vez que sua figura estiver pronta, você pode chamar {\ttfamily tight\_layout()} +para remover as margens brancas. Se houver alguma margem adicional, você pode +usar a utilidade do {\ttfamily pdfcrop} (vem com o TeX live). + + +\subsection*{\rmfamily Hachuras} +Você pode alcançar um efeito visual legal com padrões de hachuras. + +\begin{tabular}{@{}m{.774\linewidth}m{.216\linewidth}} +\begin{lstlisting}[belowskip=-\baselineskip] + cmap = plt.get_cmap("Oranges") + plt.rcParams['hatch.color'] = cmap(0.2) + plt.rcParams['hatch.linewidth'] = 8 + ax.bar(X, Y, color=cmap(0.6), hatch="/" ) +\end{lstlisting} & +\raisebox{-0.75em}{\includegraphics[width=\linewidth]{tip-hatched.pdf}} +\end{tabular} + + +\subsection*{\rmfamily Leia a documentação} + +Matplotlib tem uma documentação extensiva explicando os detalhes de cada comando +e é geralmente acompanhado por exemplos. Junto com uma galeria online gigante, +essa documentação é uma mina de ouro. + +\vfill +% +{\scriptsize + Matplotlib 3.5.0 handout for tips \& tricks. + Copyright (c) 2021 Matplotlib Development Team. + Released under a CC-BY 4.0 International License. + Supported by NumFOCUS. +\par} + + + +\end{multicols*} +\end{document}