Python Data Visualization - Seaborn

Source: Internet
Author: User
Keywords seaborn python seaborn python
One of the best ways to improve your insight is by visualizing your data: this way, you can more easily identify patterns, grasp difficult concepts and pay attention to key elements. When you use Python in data science, you are likely to have used Matplotlib, a 2D library for you to create high-quality images. Another free visualization library is seaborn, which provides a high-level interface for drawing statistical graphs.
Seaborn vs Matplotlib
As you know, Seaborn is a more advanced free library than Matplotlib, especially aiming at data visualization, but it goes further than all of these: he solves the two biggest problems of using Matplotlib, just like Michael What waskom said: Matplotlib tries to make the simple things easier and the difficult things possible, so Seaborn is to make the difficult things easier.
The biggest difficulty with Matplotlib is its default parameters, which Seaborn completely avoids.
# Import the necessary libraries
import  matplotlib.pyplot  as plt
import pandas as pd
# Initialize Figure and Axes object
fig, ax =  plt.subplots ()
# Load in data
tips =    pd.read_ csv(" https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv ""
# Create violinplot
ax.violinplot (tips["total_ bill"], vert=False)
# Show the plot
plt.show ()
# Import the necessary libraries
import  matplotlib.pyplot  as plt
import pandas as pd
import seaborn as sns
# Load the data
tips =        pd.read_ csv(" https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv ""
# Create violinplot
sns.violinplot (x = "total_ bill", data=tips)
# Show the plot
plt.show ()
The default style of Matplotlib, usually does not add color and scale label and style of axis.
Moreover, Seaborn is an extension and extension of Matplotlib. If you know Matplotlib, you have mastered most of Seaborn;
How to load data to build Seaborn image
When you use Seaborn, you can use one of the built-in datasets provided by the library itself, or you can load pandas dataframe.
Loading built-in seabed data sets
To get started with the built-in Seaborn dataset, you can use load_ Dataset() function. To view all the built-in datasets, click here to view them https://github.com/mwaskom/seaborn-data  。  Take a look at the following example to see load_ How the dataset() function works
# Import necessary libraries
import seaborn as sns
import  matplotlib.pyplot  as plt
# Load iris data
iris =  sns.load_ dataset("iris")
# Construct iris plot
sns.swarmplot (x="species", y="petal_ length", data=iris)
# Show plot
plt.show ()
Load your own dataframe dataset
Of course, for most scenarios of data visualization, you will use your own data instead of the built-in dataset of the Seaborn library. Seaborn works best with pandas dataframes and arrays that contain the entire dataset
Dataframes is a method of storing data in a rectangular grid. The rows of a dataframe do not need to contain the same type of values: they can be numbers, characters, logic, etc. For Python in particular, dataframes are integrated into the pandas library and are defined as two-dimensional markup data structures with potentially different types of columns.
The reason Seaborn is very good with dataframes is that the tags of dataframes are automatically propagated to drawings or other data structures, as shown in the first example in this tutorial, you drew a violin in Seaborn. There, you see the legend total on the x-axis_ Bill, not Matplotlib. It's going to take a lot of work.
But that doesn't mean that all the work is done - on the contrary. In many cases, you still need to manipulate your pandas dataframe to render the drawing correctly. If you want to learn more, check out the dataframes pandas tutorial or pandas foundations course in Python for datacamp
Matplotlib is still the foundation of Seaborn, which means that the structure is still the same and you need to use plt.show () display the image to you. You may have seen it from the previous example in this tutorial. In any case, here's another example, where the show() function is used to display the plot
# Import necessarily libraries
import  matplotlib.pyplot  as plt
import seaborn as sns
# Load data
titanic =  sns.load_ dataset("titanic")
# Set up a factorplot
g =  sns.factorplot ("class", "survived", "sex", data=titanic, kind="bar",         palette="muted", legend=False)
# Show plot
plt.show ()
How to use Seaborn with the default value of Matplotlib
There are also a lot of the opposite scenarios, those that use Seaborn and want to use the default settings of Matplotlib.
Previously, you could solve this problem by importing the apionly module from the Seaborn package. It is now obsolete (since July 2017). When importing Seaborn, the default style is no longer applied, so you need to call set () or set explicitly_ style(),set_ Context () and set_ One or more of palette() to get the default drawing for Seaborn or Matplotlib.
# Import Matplotlib
import  matplotlib.pyplot  as plt
# Check the available styles
plt.style.available
# Use Matplotlib defaults
plt.style.use ("classic")
How to use Seaborn color as color in Matplotlib?
How to introduce Seaborn color into Matplotlib graph. You can use color_ Palette () to define the color map and parameter n to be used_ The number of colors for colors. In this case, the example assumes that there are five tags assigned to the data points defined in data1 and data2, so that's why you pass 5 to this parameter, and you also make a list of lengths equal to N, where five integers change in variable colors
# Import the necessary libraries
import seaborn as sns
import  matplotlib.pyplot  as plt
import numpy as np
from  matplotlib.colors  import ListedColormap
# Define a variable N
N = 500
# Construct the colormap
current_ palette =  sns.color_ palette("muted", n_ colors=5)
cmap = ListedColormap( sns.color_ palette(current_ palette).as_ hex())
# Initialize the data
data1 =  np.random.randn (N)
data2 =  np.random.randn (N)
# Assume that there are 5 possible labels
colors =  np.random.randint (0,5,N)
# Create a scatter plot
plt.scatter (data1, data2, c=colors, cmap=cmap)
# Add a color bar
plt.colorbar ()
# Show the plot
plt.show ()
How to rotate label text in Seaborn
To rotate label text in a Seaborn diagram, you need to work at the diagram level. Note that in the following block of code, you can use one of the facetgrid methods, set_ Xticktabs to rotate the text
# Import the necessary libraries
import  matplotlib.pyplot  as plt
import seaborn as sns
import numpy as np
import pandas as pd
# Initialize the data
x = 10 **  np.arange (1, 10)
y = x * 2
data =  pd.DataFrame (data={'x': x, 'y': y})
# Create an lmplot
grid =  sns.lmplot ('x', 'y', data, size=7, truncate=True, scatter_ kws={"s": 100})
# Rotate the labels on x-axis
grid.set_ xticklabels(rotation=90)
# Show the plot
plt.show ()

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.