[PYTHON] [Graph drawing] I tried to write a bar graph of multiple series with matplotlib and seaborn

Introduction

I compared the drawing of multi-series bar graphs with matplotlib and seaborn.

In conclusion, ** seaborn is useful **

--Environment

Graph to draw

The left side is matplotlib and the right side is seaborn. It's the same as looking at the graphs, but seaborn is easy until you draw these. The color of the stick is the same, but seaborn is a little lighter. Maybe there is a setting somewhere like this ... グラフを描画してみた.png

Drawing flow

This is the flow until the upper bar graph is drawn.

Install library

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from io import StringIO
import numpy as np
%matplotlib inline

Create a DataFrame

data = ('Number of people,sex,age\n'
       '58,male,18-year-old\n'
       '25,male,19 years old\n'
       '42,male,20-year-old\n'
       '60,Female,18-year-old\n'
       '42,Female,19 years old\n'
       '70,Female,20-year-old\n' 
       )
df = pd.read_csv(StringIO(data), dtype={'Number of people':'int32'})
print(df)

Number of people sex age
58 male 18-year-old
25 male 19 years old
42 male 20-year-old
60 Female 18-year-old
42 Female 19 years old
70 Female 20-year-old

Draw a graph

plt.rcParams['font.family'] = 'Yu Gothic' #Avoid garbled Japanese characters with Yu Gothic by default
plt.rcParams['font.size'] = 20 #Set default font size

fig,ax = plt.subplots(1, 2, figsize=(24,10)) #Create a drawing space of 24 inches wide and 10 inches high with 1 row and 2 columns


#Bar graph drawing with matplotlib divides df data a little
labels = list(df['age'].unique()) #List the locations corresponding to the X-axis labels from df
number_male = list(df['Number of people'].loc[0:2]) #dfの上から3行のNumber of peopleの数値(男性の数値)をリスト化
number_female = list(df['Number of people'].loc[3:5]) #dfの下から3行のNumber of peopleの数値(女性の数値)をリスト化
left = np.arange(len(number_male)) #For specifying the coordinates to paste the X-axis label
print(left) #The contents of left[0 1 2]
width = 0.4 #In the case of a multi-series graph, if the coordinates of the X-axis label are only left, it will shift, so the correction amount


#Bar chart with matplotlib
ax[0].bar(x=left, height=number_male, width=width, align='center', color='royalblue') #Added bar graph for male part
ax[0].bar(x=left+width, height=number_female, width=width, align='center', color='tomato') #Added bar graph for female part
ax[0].set_xticks(left + width / 2) #Specify the axis position of the 18-year-old, 19-year-old, and 20-year-old parts
ax[0].set_xticklabels(labels=labels) #"18 years old, 19 years old, 20 years old"Specified to draw
ax[0].set_xlabel('age') #X-axis label
ax[0].set_ylabel('Number of people') #Y-axis label
ax[0].legend(list(df['sex'].unique()), title='sex', loc='upper right') #凡例の男性、女性、タイトルをsex、位置を右上へ設定
ax[0].set_title('Bar chart with matplotlib', size=30) #Set title


#Bar chart with seaborn
sns.barplot(data=df, x='age', y='Number of people', hue='sex', ax=ax[1], palette={'male':'royalblue','Female':'tomato'}) #data=Specify df, set X and Y, hue='sex'とすることでsex別で分けてくれる
ax[1].legend(loc='upper right', title='sex') #Set the legend title and position to the upper right
ax[1].set_title('Bar chart with seaborn', size=30) #Set title


plt.savefig('I tried to draw a graph.png', bbox_inches='tight', pad_inches=0.3) #Save the drawn image
plt.show() #drawing

This will draw the Bar Graph here (# graph to draw).

Number of lines
matplotlib 8
seaborn 3

Seaborn is easier to draw because you can see it! The code has two lines, a legend and a title, so you can draw multiple series of bar charts with just one line.

Recommended Posts

[Graph drawing] I tried to write a bar graph of multiple series with matplotlib and seaborn
I created a stacked bar graph with matplotlib in Python and added a data label
I tried to create a list of prime numbers with python
I tried to create Bulls and Cows with a shell program
I tried to make a mechanism of exclusive control with Go
(Matplotlib) I want to draw a graph with a size specified in pixels
I want to display multiple images with matplotlib.
I want to write to a file with Python
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to make a simple mail sending application with tkinter of Python
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I want to write an element to a file with numpy and check it.
Create a stacked graph corresponding to both positive and negative directions with matplotlib
I tried to make a simple image recognition API with Fast API and Tensorflow
I tried to create a model with the sample of Amazon SageMaker Autopilot
I wanted to know the number of lines in multiple files, so I tried to get it with a command
I tried to create a table only with Django
I tried to extract features with SIFT of OpenCV
I tried to read and save automatically with VOICEROID2 2
I tried to summarize how to use matplotlib of python
[Python] How to draw a line graph with Matplotlib
I tried to implement and learn DCGAN with PyTorch
I tried to draw a route map with Python
I tried to automatically read and save with VOICEROID2
I tried to implement time series prediction with GBDT
I tried to automatically generate a password with Python3
I tried to implement Grad-CAM with keras and tensorflow
I tried to find an alternating series with tensorflow
I tried to make something like a chatbot with the Seq2Seq model of TensorFlow
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
I tried to automate the article update of Livedoor blog with Python and selenium.
[Python] I tried to automatically create a daily report of YWT with Outlook mail
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
I tried to compare the processing speed with dplyr of R and pandas of Python
The 15th offline real-time I tried to solve the problem of how to write with python
I tried to implement a volume moving average with Quantx
I tried to predict and submit Titanic survivors with Kaggle
I tried to find the entropy of the image with python
I tried to automatically post to ChatWork at the time of deployment with fabric and ChatWork Api
I tried to find the average of the sequence with TensorFlow
How to write offline real time I tried to solve the problem of F02 with Python
I made a package to filter time series with python
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
Graph drawing method with matplotlib
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I tried to solve a combination optimization problem with Qiskit
I made a server with Python socket and ssl and tried to access it from a browser
I tried to get started with Hy ・ Define a class
I also tried to imitate the function monad and State monad with a generator in Python
I tried to make GUI tic-tac-toe with Python and Tkinter
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I tried a stochastic simulation of a bingo game with Python
I tried to divide with a deep learning language model
How to plot a lot of legends by changing the color of the graph continuously with matplotlib
When generating a large number of graphs with matplotlib, I do not want to display the graph on the screen (jupyter environment)
I tried to unlock the entrance 2 lock sesame with a single push of the AWS IoT button
I want to create a graph with wavy lines omitted in the middle with matplotlib (I want to manipulate the impression)
[Python] I tried to visualize the prize money of "ONE PIECE" over 100 million characters with matplotlib.
I tried to predict the number of domestically infected people of the new corona with a mathematical model
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use graph drawing library ♬ Basics of Matplotlib
I tried to embed a protein-protein interaction network in hyperbolic space with Poincarē embeding of gensim