current position:Home>Python Matplotlib drawing violin diagram
Python Matplotlib drawing violin diagram
2022-02-01 12:07:55 【Little cute in the circle of friends】
This is my participation 11 The fourth of the yuegengwen challenge 25 God , Check out the activity details :2021 One last more challenge
Review
matplotlib yes Python A library dedicated to rendering , We also learned before pyplot Provides drawing polylines 、 Scatter 、 Columnar 、 Square 、 Pie charts and other common images , Also provide animation Class to draw dynamic graph . At the same time, for special charts, such as quantum field diagrams applied in Physics 、 Pay attention to the box diagram of data distribution, etc . Examples of previous articles mentioned above are as follows .
-
pyplot.boxplot() Method draw box diagram , Used to show the distribution of data :matplotlib Draw a box diagram
-
pyplot.quiver() Method to draw the quantity field diagram , Commonly used in electromagnetic field analysis :matplotlib Plot the quantity field
-
pyplot.ion() Interaction mode combination for Loops can draw dynamic graphs :matplotlib Draw a dynamic diagram
-
Use animation Class to draw data dynamic graph :matplotlib Animation class
Following the last time we learned that we can quickly display the median of a set of data 、 The upper and lower quartiles 、 Box diagram of maximum and minimum value pyplot.boxplot() Method . There is also a graphical violin diagram showing the data distribution .
In this issue , We learn matplotlib.pyplot.violinplot Draw violin chart and learn related attributes ,Let's go~
1. Violin overview
-
What is the violin picture ?
- The picture of violin is similar to the shape of violin , It has the characteristics of box diagram and density diagram
- Violin chart is used to show the density of data distribution and occurrence probability
- The violin chart shows the median of the same set of data 、 Quartile range 、 density 、95% confidence interval
-
Violin diagram application scenario
- The violin diagram can be used to compare the density distribution between different samples
- The violin chart can be used to show the complete distribution of data
- Violin charts are often used to sort out discrete data before making accurate charts
- Cello charts are usually used for gene sample distribution 、 Population age distribution, etc
-
How to get violin diagram
import matplotlib.pyplot as plt
plt.violinplot(dataset)
Copy code
2. Violin chart properties
-
Set the violin map position
- keyword :vert
- The default value is :True
- When vert by True Create a vertical violin diagram
- When vert by False Create a horizontal violin diagram
-
Set the violin width
- keyword :width
- The default value is :0.5
-
Set violin data
- Set the keyword to display the mean value :showmeans, The default is False
- Set the keyword to display extreme value :showextrema, The default is True
- Set the keyword to display the median :showmedians, The default is False
-
Set violin style
- Need to use pyplot.violinplot() Return field “bodies”
- combination for Loop traversal pyplot.violinplot()["bodies"]
- call set_facecolor Set the violin color
- call set_edgecolor Set the violin border color
- call set_alpha Set the transparency of the violin chart
- call set_linestyle Set the violin border style
3. To draw a violin diagram
- Import matplotlib.pyplot class
import matplotlib.pyplot as plt
Copy code
- Use numpy In the database normal(),random(),randint() And so on data Array vector sequence
data = [np.random.normal(0,2,100)]
Copy code
- call pyplot.violinplot(data) Method to draw the violin
part = plt.violinplot(data,showmedians=True)
Copy code
- call pyplot.show() Method to render and display the violin chart
plt.show()
Copy code
- By using yplot.violinplot() Method return value , Set the color of the violin chart 、 Border styles, etc
for pc in part["bodies"]:
print(pc)
pc.set_facecolor("pink")
pc.set_edgecolor("black")
pc.set_alpha(1)
pc.set_linestyle("--")
Copy code
4. A profound
We learn to matplotlib The drawing of violin provided violinplot() After the method , Let's practice with scatter combination
- call pyplot.grid() Method to add a mesh to the canvas
- call numpy.percentile() Calculate the next quarter into numbers , Mean number , The upper quarter is divided into numbers
- call pyplot.scatter() Mark the sign of the mean on the violin chart
- call pyplot.vline() Mark the quartile on the violin chart
data = [np.random.normal(0,i,100) for i in range(2,6)]
plt.grid()
part = plt.violinplot(data,showmedians=True,widths=[0.3,0.4,0.5,0.6])
for pc in part["bodies"]:
print(pc)
pc.set_facecolor("orange")
pc.set_edgecolor("black")
pc.set_alpha(1)
pc.set_linestyle("--")
q1,me,q3 = np.percentile(data,[25,50,75],axis=1)
ind = np.arange(1,len(me)+1)
plt.scatter(ind,me,marker="o",color="r",s=50,zorder=3)
plt.vlines(ind,q1,q3,color="k",linestyles="-",lw=5)
Copy code
summary
In this issue , We are right. matplotlib.pyplot.violinplot() Method to draw violin diagram related attributes . Violin diagram combines the characteristics of box diagram and density diagram , Not only show the distribution of data , It also shows the density of the data .
The above is the content of this issue , Welcome big guys to praise and comment , See you next time ~
copyright notice
author[Little cute in the circle of friends],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011207526655.html
The sidebar is recommended
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values(python)
- leetcode 1433. Check If a String Can Break Another String(python)
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
guess what you like
-
Python crawler series - network requests
-
Python thread 01 understanding thread
-
Analysis of earthquake distribution in the past 10 years with Python~
-
You need to master these before learning Python crawlers
-
After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
-
Python uses redis
-
Python crawler - ETF fund acquisition
-
Detailed tutorial on Python operation Tencent object storage (COS)
-
[Python] comparison of list, tuple, array and bidirectional queue methods
-
Go Python 3 usage and pit Prevention Guide
Random recommended
- Python logging log error and exception exception callback method
- Learn Python quickly and take a shortcut~
- Python from 0 to 1 (day 15) - Python conditional judgment 2
- Python crawler actual combat, requests module, python to capture headlines and take beautiful pictures
- The whole activity collected 8 proxy IP sites to pave the way for the python proxy pool, and the 15th of 120 crawlers
- Why can't list be used as dictionary key value in Python
- Python from 0 to 1 (day 16) - Python conditional judgment 3
- What is the python programming language?
- Python crawler reverse webpack, a real estate management platform login password parameter encryption logic
- Python crawler reverse, a college entrance examination volunteer filling platform encrypts the parameter signsafe and decrypts the returned results
- Python simulated Login, selenium module, python identification graphic verification code to realize automatic login
- Python -- datetime (timedelta class)
- Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills
- [Python] comparison of dictionary dict, defaultdict and orderdict
- Test driven development using Django
- Face recognition practice: face recognition using Python opencv and deep learning
- leetcode 1610. Maximum Number of Visible Points(python)
- Python thread 03 thread synchronization
- Introduction and internal principles of Python's widely used concurrent processing Library Futures
- Python - progress bar artifact tqdm usage
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
- leetcode 1606. Find Servers That Handled Most Number of Requests(python)
- leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
- 06python learning notes - reading external text data
- [Python] functions, higher-order functions, anonymous functions and function attributes
- Python Networkx practice social network visualization
- Data analysis starts from scratch, and pandas reads and writes CSV data
- Python review (format string)
- [pandas learning notes 01] powerful tool set for analyzing structured data
- leetcode 147. Insertion Sort List(python)
- apache2. 4 + windows deployment Django (multi site)