search
HomeBackend DevelopmentPython TutorialIntroduction to four methods of Python data visualization (with examples)

Introduction to four methods of Python data visualization (with examples)

Nov 27, 2018 pm 03:33 PM
pandaspythondata visualizationmachine learningdeep learning

This article brings you an introduction to four methods of Python data visualization (with examples). It has certain reference value. Friends in need can refer to it. Hope it helps.

Abstract: This article describes four Python data visualization methods: heat map, two-dimensional density map, spider map, and tree map.

Data visualization is an important part of any data science or machine learning project. People often start with exploratory data analysis (EDA) to gain a deeper understanding of their data, and creating visualizations can really help make problems clearer and easier to understand, especially for those larger, high-dimensional data sets. At the end of a project, it's important to be able to present the end result in a clear, concise and convincing way that your users can understand and understand.

You may have read my previous article "5 Quick and Easy Data Visualizations in Python with Code" , which introduces 5 basic visualization methods: scatter plots, line plots, histograms, bar plots, and box plots. These five are simple yet powerful visualization methods with which you can definitely get huge gains from your data sets. In this article, we will introduce 4 other data visualization methods, but they are slightly more complicated. You can use them after reading the basic methods introduced in the previous article.

Heat Map

Heat map is a matrix representation of data, in which each matrix value is represented by a color. Different colors represent different levels, and the matrix index connects two contrasting columns or features together. Heatmaps are great at showing the relationships between multiple feature variables because one level can be viewed directly as a color. You can also see how each relationship compares to other relationships in the data set by looking at some points in the heat map. The colors do provide a simple representation as it is very intuitive.

Introduction to four methods of Python data visualization (with examples)

Now look at the code: compared to the matplotlib library, the seaborn library can be used for more advanced charts and usually requires more components, Such as more colors, graphics or variables. The Matplotlib library is used to display charts, numpy is used to generate data, and pandas is used for control. Plotting is just a simple seaborn function call, and if you find something visually special, you can also set the color map through this function.

# Importing libs
importseaborn as sns
import pandas aspd
importnumpyasnp
importmatplotlib.pyplotasplt

# Create a random dataset
data=pd.DataFrame(np.random.random((10,6)), columns=["Iron Man","CaptainAmerica","BlackWidow","Thor","Hulk", "Hawkeye"])

print(data)

# Plot the heatmap
heatmap_plot=sns.heatmap(data, center=0, cmap='gist_ncar')

plt.show()

Two-dimensional density plot (2D Density Plot)

The two-dimensional density plot is a simple extension of the one-dimensional version, which can see the probability distribution of two variables . Let’s look at the 2D density plot below. The scale on the right represents the probability of each point in color. The highest probability, looking at the data set, seems to be about 0.5 size and 1.4-ish speed. As you can see, 2D density plots are great for quickly determining the areas of the data that are most concentrated for two variables, rather than just one variable like 1D density plots. Two-dimensional density plots are particularly useful when you have two variables that are important to the output and want to understand how they together contribute to the distribution of the output.

Introduction to four methods of Python data visualization (with examples)

Seaborn’s code is super simple and we will introduce it by creating a skewed distribution. If you find that certain colors and shades are more visually distinctive, most of the optional parameters are for a clearer look.

Spider Plot

Spider diagram is one of the best ways to display one-to-many relationships. That is, you can plot and view the values ​​of multiple variables as distinct from a single variable or category. In a spider diagram, the properties of one variable relative to another are apparent because the area and length vary in some directions. If you want to see how the variables stack up for several categories, plot them side by side. In the image below, it's easy to compare the different attributes of three movie characters and see where their strengths lie!

Introduction to four methods of Python data visualization (with examples)

This time we will be able to use matplotlib directly to create visualizations instead of seaborn. The angle at which each attribute lies needs to be calculated because we want them to be evenly spaced along the circumference. We will place labels at each calculated angle and then plot the value as a point whose distance from the center depends on its value or level. Finally, for clarity, we'll fill the area contained by the lines connecting the property points with a semi-transparent color.

# Import libs
import pandas aspd
importseabornassns
importnumpyasnp
importmatplotlib.pyplotasplt

# Get the data
df=pd.read_csv("avengers_data.csv")
print(df)

"""
   #             Name  Attack  Defense  Speed  Range  Health
0  1         Iron Man      83       80     75     70      70
1  2  Captain America      60       62     63     80      80
2  3             Thor      80       82     83    100     100
3  3             Hulk      80      100     67     44      92
4  4      Black Widow      52       43     60     50      65
5  5          Hawkeye      58       64     58     80      65

"""

# Get the data for Iron Man
labels=np.array(["Attack","Defense","Speed","Range","Health"])
stats=df.loc[0,labels].values

# Make some calculations for the plot
angles=np.linspace(0, 2*np.pi, len(labels), endpoint=False)
stats=np.concatenate((stats,[stats[0]]))
angles=np.concatenate((angles,[angles[0]]))

# Plot stuff
fig=plt.figure()
ax=fig.add_subplot(111, polar=True)
ax.plot(angles, stats, 'o-', linewidth=2)
ax.fill(angles, stats, alpha=0.25)
ax.set_thetagrids(angles *180/np.pi, labels)
ax.set_title([df.loc[0,"Name"]])
ax.grid(True)

plt.show()

Tree Diagram

We have been using tree diagrams since elementary school. Tree diagrams are natural, intuitive, and easy to explain. Nodes that are directly connected are closely related and are very different from nodes that have multiple connections. In the image below, I have plotted a small portion of the

Pokemon with stats data set from Kaggle based on statistics:

HP, Attack, Defense, Special Attack, Special Defense, Speed

因此,与stats wise最匹配的Pokemon将紧密连接在一起。例如,我们看到,在顶部,Arbok和Fearow是直接连接的,而且,如果我们查看数据,Arbok总共有438个,而Fearow有442个,非常接近。但是一旦我们移动到Raticate,我们得到的总数是413,这与Arbok和Fearow的差别很大,这就是它们被分开的原因。当我们移动树的时候,基于相似性,Pokemon被分的组越来越多。在绿色组中的Pokemon相互之间比红色组中的更相似,即使没有直接的绿色连接。

Introduction to four methods of Python data visualization (with examples)

对于树形图,我们实际上要使用Scipy的。在查看了数据集之后,我们将去掉字符串类型的列。我们这么做只是为了要得到正确的可视化结果,但在实践中,最好是把这些字符串转换成分类变量,为了得到更好的结果和进行比较,我们还设置了数据帧索引,以便能够适当地用它作为引用每个节点的列。最后,在Scipy中计算和绘制树形图是非常简单的事了。

# Import libs
import pandas aspd
frommatplotlibimportpyplotasplt
fromscipy.clusterimport hierarchy
importnumpyasnp
# Read in the dataset
# Drop any fields that are strings
# Only get the first 40 because this dataset is big
df=pd.read_csv('Pokemon.csv')
df=df.set_index('Name')
del df.index.name
df=df.drop(["Type 1", "Type 2", "Legendary"], axis=1)
df=df.head(n=40)
# Calculate the distance between each sample
Z =hierarchy.linkage(df, 'ward')
# Orientation our tree
hierarchy.dendrogram(Z, orientation="left", labels=df.index)
plt.show()


The above is the detailed content of Introduction to four methods of Python data visualization (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor