How to Plot Data in Python with Pandas?

Source: Internet
Author: User
Keywords how to plot data in python python how to plot data how to plot graph in python
Pandas is a very popular Python data manipulation library. Learn how to use its API to plot data.
In a series of articles about Python-based drawing libraries, we will conduct a conceptual study of drawing using Pandas, a very popular Python data manipulation library. Pandas is a standard tool in Python for scalable data conversion. It has also become a popular method for importing and exporting data from CSV and Excel formats.

Alibaba Cloud Simple Application Server:  Anti COVID-19 SME Enablement Program
$300 coupon package for all new SMEs and a $500 coupon for paying customers.


In addition, it also contains a very good drawing API. This is very convenient. You have stored the data in a Pandas DataFrame, so why not use the same library for drawing?

In this series, we will make the same multiple bar histograms in each library so that we can compare how they work. The data we use is the result of the British election from 1966 to 2020:

Self-drawn data

Before continuing, please note that you may need to adjust the Python environment to run this code, including:

  • Running the latest version of Python (instructions for Linux, Mac and Windows)
  • Make sure you are running a Python version compatible with these libraries
The data is available online and can be imported using Pandas:
import pandas as pddf = pd.read_csv('https://anvil.works/blog/img/plotting-in-python/uk-election-results.csv')
Now we are ready. In this series of articles, we have seen some impressively simple APIs, but Pandas is sure to win.

To draw a histogram grouped by year and each party on the x-axis, I just need to do this:
import matplotlib.pyplot as pltax = df.plot.bar(x='year')plt.show()

With only four rows, this is definitely the best multi-bar histogram we created in this series.

I use the data in a wide format, which means that there is a column for each party:
  year  conservative  labour  liberal  others0       1966           253     364       12       11       1970           330     287        6       72   Feb 1974           297     301       14      18..       ...           ...     ...      ...     ...12      2015           330     232        8      8013      2017           317     262       12      5914      2019           365     202       11      72

This means that Pandas will automatically know how I want to group. If I want to group differently, Pandas can easily reorganize the DataFrame.

Like Seaborn, Pandas' drawing function is an abstraction on top of Matplotlib, which is why it is necessary to call Matplotlib's plt.show() function to actually generate the drawing.

It looks like this:

It looks great, especially if it is so simple! Let's style it to make it look like Matplotlib's example.

Adjust style

We can easily adjust the style by accessing the underlying Matplotlib method.

First, we can color the histogram by passing the Matplotlib color table to the drawing function:
from matplotlib.colors import ListedColormapcmap = ListedColormap(['#0343df', '#e50000', '#ffff14', '#929591'])ax = df.plot.bar(x='year', colormap=cmap)

We can use the return value of the drawing function to set the axis label and title, it is just a Matplotlib Axis object.
ax.set_xlabel(None)ax.set_ylabel('Seats')ax.set_title('UK election results')

This is what it looks like now:

This is almost the same as the Matplotlib version above, but only 8 lines of code are used instead of 16 lines! My inner code master is very happy.


Abstraction must be escapeable

Like Seaborn, the ability to access the Matplotlib API down to make detailed adjustments is really helpful. This is a good example of an abstract emergency exit that makes it both powerful and simple.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.