Plots With Python

Posted on by admin
Plots With Python Rating: 3,8/5 9452 reviews

Data visualization is a technique that allows data scientists to convert raw data into charts and plots that generate valuable insights. Charts reduce the complexity of the data and make it easier to understand for any user.

Creating a Basic Plot Using Matplotlib To create a plot in Matplotlib is a simple task, and can be achieved with a single line of code along with some input parameters. The code below shows how to do simple plotting with a single figure. Import matplotlib.pyplot as plt.

Make Plots With Python

There are many tools to perform data visualization, such as Tableau, Power BI, ChartBlocks, and more, which are no-code tools. They are very powerful tools, and they have their audience. However, when working with raw data that requires transformation and a good playground for data, Python is an excellent choice.

Though more complicated as it requires programming knowledge, Python allows you to perform any manipulation, transformation, and visualization of your data. It is ideal for data scientists.

There are many reasons why Python is the best choice for data science, but one of the most important ones is its ecosystem of libraries. Many great libraries are available for Python to work with data like numpy, pandas, matplotlib, tensorflow.

Matplotlib is probably the most recognized plotting library out there, available for Python and other programming languages like R. It is its level of customization and operability that set it in the first place. However, some actions or customizations can be hard to deal with when using it.

Developers created a new library based on matplotlib called seaborn. Seaborn is as powerful as matplotlib while also providing an abstraction to simplify plots and bring some unique features.

In this article, we will focus on how to work with Seaborn to create best-in-class plots. If you want to follow along you can create your own project or simply check out my seaborn guide project on GitHub.

What is Seaborn?

Seaborn is a library for making statistical graphics in Python. It builds on top of matplotlib and integrates closely with pandas data structures.

  • To create a Q-Q plot for this dataset, we can use the qqplot function from the statsmodels library: import statsmodels.api as sm import matplotlib.pyplot as plt #create Q-Q plot with 45-degree line added to plot fig = sm.qqplot(data, line='45') plt.show In a Q-Q plot, the x-axis displays the theoretical quantiles. This means it doesn’t.
  • As others have answered, scatter or plot will generate the plot you want. I suggest two refinements to answers that are already here: Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.

Seaborn design allows you to explore and understand your data quickly. Seaborn works by capturing entire dataframes or arrays containing all your data and performing all the internal functions necessary for semantic mapping and statistical aggregation to convert data into informative plots.

It abstracts complexity while allowing you to design your plots to your requirements.

Installing Seaborn

With

Installing seaborn is as easy as installing one library using your favorite Python package manager. When installing seaborn, the library will install its dependencies, including matplotlib, pandas, numpy, and scipy.

Let’s then install seaborn, and of course, also the package notebook to get access to our data playground.

Additionally, we are going to import a few modules before we get started.

Building your first plots

Before we can start plotting anything, we need data. The beauty of seaborn is that it works directly with pandas dataframes, making it super convenient. Even more so, the library comes with some built-in datasets that you can now load from code, no need to manually downloading files.

Let’s see how that works by loading a dataset that contains information about flights.

yearmonthpassengers
01949Jan112
11949Feb118
21949Mar132
31949Apr129
41949May121

All the magic happens when calling the function load_dataset, which expects the name of the data to be loaded and returns a dataframe. All these datasets are available on a GitHub repository.

Scatter Plot

A scatter plot is a diagram that displays points based on two dimensions of the dataset. Creating a scatter plot in the seaborn library is so simple and with just one line of code.

Very easy, right? The function scatterplot expects the dataset we want to plot and the columns representing the x and y axis.

Line Plot

This plot draws a line that represents the revolution of continuous or categorical data. It is a popular and known type of chart, and it’s super easy to produce. Similarly to before, we use the function lineplot with the dataset and the columns representing the x and y axis. Seaborn will do the rest.

Bar Plot

It is probably the best-known type of chart, and as you may have predicted, we can plot this type of plot with seaborn in the same way we do for lines and scatter plots by using the function barplot.

It’s very colorful, I know, we will learn how to customize it later on in the guide.

Extending with matplotlib

Seaborn builds on top of matplotlib, extending its functionality and abstracting complexity. With that said, it does not limit its capabilities. Any seaborn chart can be customized using functions from the matplotlib library. It can come in handy for specific operations and allows seaborn to leverage the power of matplotlib without having to rewrite all its functions.

Let’s say that you, for example, want to plot multiple graphs simultaneously using seaborn; then you could use the subplot function from matplotlib.

Using the subplot function, we can draw more than one chart on a single plot. The function takes three parameters, the first is the number of rows, the second is the number of columns, and the last one is the plot number.

We are rendering a seaborn chart in each subplot, mixing matplotlib with seaborn functions.

Seaborn loves Pandas

We already talked about this, but seaborn loves pandas to such an extent that all its functions build on top of the pandas dataframe. So far, we saw examples of using seaborn with pre-loaded data, but what if we want to draw a plot from data we already have loaded using pandas?

Making beautiful plots with styles

Seaborn gives you the ability to change your graphs’ interface, and it provides five different styles out of the box: darkgrid, whitegrid, dark, white, and ticks.

Here is another example

Cool use cases

We know the basics of seaborn, now let’s get them into practice by building multiple charts over the same dataset. In our case, we will use the dataset “tips” that you can download directly using seaborn.

First, load the dataset.

total_billtipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4

I like to print the first few rows of the data set to get a feeling of the columns and the data itself. Usually, I use some pandas functions to fix some data issues like null values and add information to the data set that may be helpful. You can read more about this on the guide to working with pandas.

Let’s create an additional column to the data set with the percentage that represents the tip amount over the total of the bill.

Now our data frame looks like the following:

total_billtipsexsmokerdaytimesizetip_percentage
016.991.01FemaleNoSunDinner20.059447
110.341.66MaleNoSunDinner30.160542
221.013.50MaleNoSunDinner30.166587
323.683.31MaleNoSunDinner20.139780
424.593.61FemaleNoSunDinner40.146808

Next, we can start plotting some charts.

Multiple Plots In Python

Understanding tip percentages

Let’s try first to understand the tip percentage distribution. For that, we can use histplot that will generate a histogram chart.

That’s good, we had to customize the binwidth property to make it more readable, but now we can quickly appreciate our understanding of the data. Most customers would tip between 15 to 20%, and we have some edge cases where the tip is over 70%. Those values are anomalies, and they are always worth exploring to determine if the values are errors or not.

It would also be interesting to know if the tip percentage changes depending on the moment of the day,

This time we loaded the chart with the full dataset instead of just one column, and then we set the property hue to the column time. This will force the chart to use different colors for each value of time and add a legend to it.

Customizing Plots With Python Matplotlib

Total of tips per day of the week

Another interesting metric is to know how much money in tips can the personnel expect depending on the day of the week.

It looks like Friday is a good day to stay home.

Impact of table size and day on the tip

Sometimes we want to understand how to variables play together to determine output. For example, how do the day of the week and the table size impact the tip percentage?

To draw the next chart we will combine the pivot function of pandas to pre-process the information and then draw a heatmap chart.

Conclusion

Of course, there’s much more of what we can do with seaborn, and you can learn more use cases by visiting the official documentation.

I hope that you enjoyed this article as much as I enjoyed writing it.

Thanks for reading!

Plotly's Python graphing library makes interactive, publication-quality graphs. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, polar charts, and bubble charts.
Plotly.py is free and open source and you can view the source, report issues or contribute on GitHub.


Our recommended IDE for Plotly's Python graphing library is Dash Enterprise's Data Science Workspaces, which has both Jupyter notebook and Python code file support.
Find out if your company is using Dash Enterprise.

Install Dash Enterprise on Azure Install Dash Enterprise on AWS

More Fundamentals »
More AI and ML »
More Basic Charts »
More Statistical Charts »
More Scientific Charts »
More Financial Charts »
More Maps »
More 3D Charts »
More Subplots »

Making Plots With Python

Jupyter Widgets Interaction

Python Plot A List

Add Custom Controls