Construindo Plots com Matplotlib em Python

Data Science Academy
13 Mar 202307:37

Summary

TLDRThis educational video script introduces viewers to creating graphs using Python's Matplotlib library. The instructor demonstrates how to import Matplotlib and its pyplot package, creating simple plots with minimal code. The script emphasizes the ease of graph creation, showcasing customization options like labels, titles, and legends. It introduces the concept of 'grammar of graphics,' highlighting the layers involved in building a graph. The tutorial aims to simplify data visualization, making Python programming for graphs accessible.

Takeaways

  • 📊 The script introduces the concept of creating plots or graphs as a visual representation of data using Python.
  • 💻 It mentions the use of the Matplotlib library, specifically the pyplot package, for creating and customizing plots within a Jupyter notebook.
  • 🔧 The script explains that Matplotlib is not just a plotting library but a comprehensive tool for data visualization in data analysis, machine learning, and more.
  • 📈 The speaker demonstrates how to create a simple plot using the `plot` method of the pyplot module, passing two lists of numbers as arguments.
  • 🖼️ The script highlights the ability to customize plots with various parameters, such as axis labels, titles, and colors, to enhance data interpretation.
  • 🛠️ The concept of 'grammar of graphics' is introduced, which is a set of rules and best practices for creating effective and understandable graphs.
  • 🎨 The script showcases how to add layers to a plot, such as data layers, legends, text, and even multiple plots on top of each other.
  • 📝 The speaker emphasizes the ease of creating plots with Python, suggesting that with just a few lines of code, one can produce sophisticated visualizations.
  • 🌈 Examples are given on how to add labels to axes, titles to plots, and legends to differentiate between data series within the same graph.
  • 🔑 The script concludes by encouraging viewers to learn more about the 'grammar of graphics' and to explore the full potential of data visualization tools like Matplotlib.

Q & A

  • What is the main focus of the video script?

    -The main focus of the video script is to introduce the concept of creating graphs or plots using Python, specifically with the Matplotlib library.

  • Why is Matplotlib a popular choice for data visualization in Python?

    -Matplotlib is popular because it is a comprehensive library for creating static, interactive, and animated visualizations in Python, widely used in data analysis, scientific computing, and machine learning.

  • What is the term used to describe a graphical representation of data in the script?

    -The term used to describe a graphical representation of data is 'plot' or 'pote' in Portuguese.

  • Which specific package within Matplotlib is mentioned for creating and customizing plots?

    -The specific package mentioned within Matplotlib for creating and customizing plots is 'pyplot'.

  • How does the script suggest importing the 'pyplot' package from Matplotlib?

    -The script suggests importing 'pyplot' from Matplotlib by using 'from matplotlib import pyplot as plt', where 'plt' is an alias for 'pyplot'.

  • What is the purpose of the 'plt.show()' function in the context of the script?

    -The 'plt.show()' function is used to display the plot that has been created within the script.

  • What does the script imply about the ease of creating plots in Python over time?

    -The script implies that creating plots in Python has become increasingly easier over time, with the evolution of libraries like Matplotlib making the process more straightforward.

  • What is the term used in the script to describe the area where the graph is drawn?

    -The term used to describe the area where the graph is drawn is 'plot area'.

  • How can the script's content be complemented with additional information?

    -The script's content can be complemented by reading the definitions provided in the Tijuca notebook, which are meant to supplement the video's explanations.

  • What is the concept introduced in the script that compares creating a plot to constructing layers?

    -The concept introduced is the 'grammar of graphics', which likens creating a plot to building a set of layers, such as data, legend, text, and multiple plots on top of each other.

  • How does the script demonstrate customizing a plot with labels and titles?

    -The script demonstrates customizing a plot by using methods like 'xlabel', 'ylabel', and 'title' to add labels and titles to the x-axis, y-axis, and the overall plot, respectively.

Outlines

00:00

📊 Introduction to Data Visualization with Plotly in Python

The speaker begins by introducing the concept of data visualization through graphical representations, specifically mentioning the use of plots or charts to visualize data. They emphasize the wide application of this technique in data analysis, science, and machine learning. The speaker introduces Plotly, a library for creating interactive and visually appealing graphs, and notes that it is part of the larger Matplotlib library, which offers a broader set of functionalities. They also highlight the importance of the 'plotly' package within Matplotlib for creating and customizing plots, referring to it affectionately as 'plt'. The tutorial aims to guide viewers on how to create these plots within a Jupyter notebook environment, using simple Python code. The speaker also touches on the idea that creating plots within the notebook is more interactive and visually integrated compared to saving them separately. The process of creating a basic plot with two lists of data and using the 'show' method to display it is explained. The speaker concludes by suggesting that creating plots in Python is straightforward and will demonstrate how to customize these plots with more code examples in the future.

05:01

🌈 Customizing Plots with Labels, Titles, and Legends

In this segment, the speaker delves into the customization of plots by adding labels to the x and y axes, as well as a title for the graph. They demonstrate how to use the 'xlabel' and 'ylabel' methods to assign these labels, and the 'title' method to add a title to the plot. The speaker also introduces the concept of 'grammar of graphics', which is a framework for constructing graphs by layering different elements such as data, legends, and text. They mention that creating a plot is akin to creating a layered composition, each with its own significance. The speaker uses the example of 'ggplot2' from the R language, which is built on the grammar of graphics, to illustrate this concept. They then proceed to create a more customized plot by defining x and y labels directly within the 'plot' function and adding a legend using the 'legend' method. The speaker concludes by emphasizing the customizability of plots, including the ability to position the legend and title at various locations within the graph, and hints at further customization techniques to be covered in subsequent videos.

Mindmap

Keywords

💡Plot

In the context of the video, 'plot' refers to a graphical representation of data. It is a fundamental concept in data analysis, used to visualize data in a graphical form. The script mentions that the presenter will use a 'plot' to look at data visually, which is a common practice in fields like data science, machine learning, and scientific research. The term is used to describe the action of creating a visual representation of data points, lines, or other graphical elements that can be manipulated and customized using libraries like Matplotlib in Python.

💡Matplotlib

Matplotlib is a plotting library mentioned in the script, which is widely used for creating static, animated, and interactive visualizations in Python. The video script refers to it as 'match Pot Lib' in a playful manner, indicating that it is a library for building graphical representations or plots. The script explains that Matplotlib has a package called 'pyplot' which is specifically for creating and customizing plots, highlighting its importance in the data visualization process.

💡Pyplot

Pyplot is a module within the Matplotlib library, used for making 2D plots. The script introduces 'pyplot' as a package within Matplotlib that is essential for the construction and customization of plots. The presenter uses 'plt' as an alias for 'pyplot', which simplifies the code and makes it more readable. The script demonstrates how to use the 'plot' method from 'pyplot' to create a basic line plot by passing two lists of numbers.

💡Data Visualization

Data visualization is the process of representing data in a graphical format to make it easier to understand and analyze. The video script emphasizes the importance of visualizing data through plots, as it allows for a more intuitive interpretation of the information. The presenter discusses how data visualization is used in various fields, including data analysis and machine learning, to represent data in a graphical form.

💡Customization

Customization in the context of the video refers to the ability to modify the appearance and behavior of plots to better suit the needs of the data presentation. The script explains that with libraries like Matplotlib, one can customize various aspects of a plot, such as axis labels, titles, and line colors. The presenter demonstrates how to add labels and titles to the axes of a plot, showcasing the flexibility of data visualization tools.

💡Legend

A legend in a plot is a key that explains the meaning of the various graphical elements, such as lines or colors, used in the plot. The video script mentions adding a legend to a plot to provide context and clarity to the viewer. It is an important aspect of data visualization as it helps in distinguishing between different sets of data presented in a single plot.

💡Axis Labels

Axis labels are textual descriptions that appear on the axes of a plot, indicating what each axis represents. In the script, the presenter uses the 'xlabel' and 'ylabel' methods to add labels to the x-axis and y-axis, respectively. These labels are crucial for providing information about the variables or data dimensions being plotted.

💡Title

A title in a plot is a text that gives a brief description or a name to the plot. The video script includes an example where the presenter adds a title to a plot using the 'title' method. The title is an essential element in data visualization as it provides a quick understanding of what the plot represents.

💡Jupyter Notebook

Jupyter Notebook is an open-source web application that allows for interactive computing across various programming languages. The script mentions using Jupyter Notebook for creating plots within the browser, which is a common practice for data scientists and analysts. It allows for the combination of code, visualizations, and narrative text in a single document, making it an ideal platform for data exploration and presentation.

💡Magic Command

In the context of Jupyter Notebook, a magic command is a special command that is preceded by one or two percent signs (%). The script refers to 'magic command' when discussing the need to be aware of the environment in which the code is running. Magic commands are used for various purposes, such as loading external modules or configuring the notebook's behavior.

💡Grammar of Graphics

The 'Grammar of Graphics' is a concept mentioned in the script that refers to a set of principles for creating statistical graphics. The presenter explains that a plot is like a language, with layers such as data, legends, text, and other graphical elements that are built upon each other. The concept is foundational in understanding how to construct complex and informative visualizations by layering different components.

Highlights

Introduction to constructing the first graphs using Matplotlib in Python.

Explanation of the term 'plot' as a graphical representation of data.

Matplotlib is a library for creating visual representations, not just for plotting.

Importing the 'pyplot' package from Matplotlib for graph creation and customization.

Using 'plt' as a nickname for 'pyplot' to create graphs within the browser page.

Creating the first plot with the 'plot' method and displaying it using 'plt.show'.

The simplicity of creating graphs in Python with just a few lines of code.

Evolution of graph creation becoming easier over time with Matplotlib.

Definition of the plot area and the ability to manipulate it with Matplotlib.

Customization options for the plot area, including axis scales and line colors.

Adding labels and titles to the plot using 'xlabel', 'ylabel', and 'title' methods.

Concept of the 'grammar of graphics' as a framework for creating layered and complex plots.

Introduction to the 'ggplot2' library in R, which is based on the grammar of graphics.

Creating a more customized plot with labels and legends using the 'plot' method and 'legend' function.

Customization of plot legends, including position and text.

Continuation of the tutorial in the next video for further exploration of graph customization.

Transcripts

play00:00

[Música]

play00:05

já vamos construir os primeiros gráficos

play00:08

os primeiros potes comete pote Lib em

play00:11

Python por gentileza Me acompanhe ao

play00:14

longo do Tijuca notebook você vai

play00:16

encontrar uma série de definições que

play00:19

complementam as minhas explicações então

play00:22

você pode dar um pause no vídeo fazer a

play00:25

leitura do texto que você vê agora aí na

play00:27

sua tela ou se por acaso já abriu junto

play00:29

notebook que eu fornecer ao final do

play00:31

capítulo também pode dar um pause no

play00:33

vídeo fazer a leitura você vai

play00:34

complementar tudo que eu vou explicar ok

play00:37

O que é um pote é uma representação

play00:40

gráfica de dados tudo bem eu quero olhar

play00:44

para os dados de maneira visual de

play00:46

maneira gráfica nesse caso eu vou usar

play00:48

um pote Ou se você quiser chamar apenas

play00:51

de gráfico tudo bem mas é uma

play00:52

representação gráfica de dados esse tema

play00:55

plot é amplamente usado em análise de

play00:57

dados ciência de dados machine learning

play00:59

O próprio match Pot Lib não é tem plot

play01:02

no nome o que indica que ela é

play01:04

biblioteca para construção de gráficos

play01:06

de representações visuais tudo bem bom o

play01:10

médico eu importei aqui em cima ele tem

play01:13

um conjunto de funções para você criar

play01:15

os gráficos só que dentro do match Lib

play01:18

tem um outro pacote chamado pai plot que

play01:22

específico para construção e

play01:24

customização de gráficos então é um

play01:26

pacote dentro do outro o pai plot é tão

play01:29

incrível que tem que usar o pylot Ok ele

play01:33

faz com que você dorme o médico pote Lib

play01:35

ainda melhor então eu vou importar a

play01:38

partir do matchport Lib o pai plot vou

play01:40

chamar de plt um apelido carinhoso eu

play01:43

vou colocar o recentemente pote libre

play01:46

para que os gráficos sejam criados nesta

play01:49

página do meu navegador porque é

play01:52

possível criar os gráficos fora desta

play01:54

página ele abrir uma outra página e

play01:57

criar o gráfico separado para você mas

play01:59

não é o que eu quero eu quero sempre

play02:00

criar os gráficos dentro do jogo do

play02:02

notebook pelo menos aqui para explicar

play02:04

os tudo bem tudo que tiver presente aqui

play02:08

no começo normalmente a operador Mágico

play02:10

do Júpiter notebook hein Não é comando

play02:12

Python fica atento a isso vamos então

play02:15

importar o pai pode e na sequência vou

play02:18

criar o primeiro plot a partir do plt

play02:20

que é o apelido carinhoso que demos para

play02:22

o pai plot do médio porte Lib eu vou

play02:25

chamar o método plot nesse método veja

play02:28

que eu tô passando entre parênteses duas

play02:31

listas Python concorda que são duas

play02:33

listas Por que são duas listas abre e

play02:36

fecha a colchetes não é isso conceito de

play02:38

lista hein pai Então são duas listas de

play02:40

números primeira lista segunda lista o

play02:43

método plot vai pegar esses valores e

play02:46

vai criar um gráfico para nós E aí eu

play02:48

estou usando o plt show show é mostrar

play02:50

né para indicar por gentileza

play02:53

cria o gráfico e mostre o que eu posso

play02:56

criar o gráfico e salvar em disco por

play02:58

exemplo eu não preciso visualizar não é

play03:00

Ou seja não precisa olhar para o gráfico

play03:02

aqui no Júpiter Eu posso salvar em disco

play03:04

nesse caso eu quero é olhar para o

play03:06

gráfico então eu uso o plt show executa

play03:09

e pronto gráfico criado com sucesso

play03:12

usamos duas linhas de código então essa

play03:16

coisa de que programar em Python para

play03:19

criar gráficos é difícil não é bem assim

play03:21

não é nós podemos criar bons gráficos

play03:24

com uma linha de código vou mostrar

play03:27

vários exemplos para você bem como

play03:29

podemos customizar os gráficos com

play03:31

várias linhas de código mas ao longo dos

play03:35

anos a criação dos gráficos

play03:37

vem se tornando cada vez mais fácil eu

play03:40

já uso match Pocket livre há um bom

play03:41

tempo já ensina que na dsa também é um

play03:43

bom tempo é incrível acompanhar a

play03:45

evolução como vai se tornando cada vez

play03:47

mais fácil a criação de gráficos ao

play03:49

longo do tempo bom isso aqui que você vê

play03:51

é um gráfico ou se você preferir é um

play03:55

pote ou ainda uma representação gráfica

play03:58

dos dados tudo isso aqui toda essa área

play04:01

onde o gráfico foi desenhado nós

play04:03

chamamos de área de plota e eu posso

play04:06

manipular essa área de plotagem através

play04:08

de parâmetros com Netpoint Lib o que eu

play04:11

vou ensinar para você daqui a pouquinho

play04:12

Inclusive eu posso pegar essa área de

play04:14

plotagem e dividir em duas áreas duas

play04:17

sub áreas ou em quatro sub áreas ou em 8

play04:20

sub áreas criar vários gráficos em

play04:22

paralelo um em cima do outro posso

play04:25

manipular tudo isso na hora que tiver

play04:27

criando os gráficos

play04:28

veja ainda que ele colocou os valores

play04:31

não é da escala no eixo X e no eixo Y

play04:34

isso aí pode ser manipulado a cor da

play04:37

linha também pode ser modificada eu

play04:40

posso adicionar legenda por exemplo tudo

play04:42

isso aqui customizado Vamos combinar

play04:44

assim tudo isso aqui pode ser

play04:46

customizado como é que pode vejamos

play04:48

então outros e outros exemplos vou criar

play04:51

agora mais duas listas x e y vou então

play04:54

chamar o plot e passar X e Y como

play04:56

argumento ao invés de passar direto a

play04:58

lista como eu fiz aqui em cima vou

play05:00

passar as duas variáveis x y agora eu

play05:03

vou acrescentar Rainbow e x aí eu chamo

play05:06

o método x Label e aí coloco entre aspas

play05:10

simples o texto que eu quero mesma coisa

play05:12

para o leigo Y também vou colocar um

play05:15

título então eu coloco a função tytow

play05:18

indicando que eu quero um título desse

play05:20

caso o texto entre aspas eu quero

play05:22

visualizar o gráfico chama então o

play05:24

método show vamos criar as duas

play05:25

variáveis na sequência criamos o gráfico

play05:28

veja que agora o gráfico já está bem

play05:30

mais customizado não é então nós

play05:32

colocamos Label em x e y colocamos o

play05:35

título tudo isso usando outros métodos

play05:39

do plt aqui ó só você chamar os métodos

play05:41

você vai acrescentando camadas aliás

play05:44

aqui tem um conceito interessantíssimo

play05:46

que é o conceito de gramática dos

play05:48

gráficos já ouvi falar sobre isso nunca

play05:51

ouviu falar Recomendo o último custo da

play05:53

formação cientista de dados que eu

play05:54

ensino completamente a gramática dos

play05:56

gráficos um gráfico de fato é um

play05:59

conjunto de camadas você vai desenhando

play06:01

camadas uma acima da outra tem a camada

play06:04

de dados tem a camada de legenda tem a

play06:07

camada de texto tem camada de um gráfico

play06:08

em cima do outro esse é o conceito de

play06:11

gramática dos gráficos Aliás o ggprote 2

play06:13

que eu apresentei aí no vídeo introdução

play06:16

deste Capítulo GG significa gramática

play06:18

dos gráficos no termo inglês obviamente

play06:21

né então GG Lote 2 da linguagem R foi

play06:24

criado exatamente em cima do conceito de

play06:27

gramática dos gráficos você acha que

play06:29

criar um gráfico é só desenhar assim uma

play06:31

imagem não criar um gráfico é quase uma

play06:33

ciência por si só você tem uma série de

play06:36

regras de padrões de boas práticas que

play06:39

aliás também ensina no curso gratuito de

play06:41

powerbiai aqui na dsa se quiser aprender

play06:43

completamente o conceito de gramática

play06:45

dos gráficos é o último custo da

play06:46

formação cientista de dados mas um

play06:49

exemplo vou criar agora X2 e Y2 duas

play06:52

novas listas vou então chamar o pote e

play06:56

aí vou colocar X2 Y2 já dizendo que eu

play06:59

quero Label ou seja eu posso colocar o

play07:02

Label a partir da própria função plot

play07:05

usar um outro método à parte eu então

play07:07

chama o método legend para poder colocar

play07:10

uma legenda ele vai colocar

play07:11

automaticamente e o plt show para poder

play07:14

mostrar o resultado E aí está para você

play07:16

eu então definir o Label e eu disse que

play07:19

eu quero mostrar a legenda ele pega o

play07:21

Label coloca na legenda para você que

play07:23

esse texto né que aparece aqui no canto

play07:25

superior esquerdo aliás dá para você

play07:27

colocar alergia na hora que você quiser

play07:28

do lado esquerdo direito na parte de

play07:31

cima de baixo tudo isso também é

play07:33

customizável continuamos no próximo

play07:35

vídeo tá

Rate This

5.0 / 5 (0 votes)

Related Tags
Data VisualizationPython CodingMatplotlibPlotting TutorialData ScienceGraphical RepresentationCoding BasicsScientific AnalysisMachine LearningCustomization Techniques