当前位置:网站首页>Visual introduction to Matplotlib and plotnine
Visual introduction to Matplotlib and plotnine
2022-06-27 01:00:00 【Moon fish and fourteen elements】
Matplotlib yes Python in similar MATLAB Drawing tools for , The author often uses Matlab, So think of it as an introduction to data visualization , But its style is often more regular , The grammar is also more complex to adjust .Plotnine It makes up for Python Lack of data , similar R Language , Can be said to be ggplot2 stay Python Porting version on , The author had a preliminary contact with the American competition because of its exquisite drawing style , It is easier to adjust the grammar , But the Chinese language is not supported , There is also less relevant information . Now take advantage of the summer semester , Introduce their basic usage .
The architecture
about Matplotlib for , What it does is a serial addition , have Layer upon layer Characteristics . At the bottom Canvas( Drawing board ) , Build on Figure( canvas ) , And then build on the canvas Axes( Drawing area ) , And the axis (axis) 、 legend (legend) And other auxiliary display layers and image layers are built on Axes above , Drawing object oriented .
This is very similar to the process of drawing with a drawing board , Let's find a drawing board first , Then lay a canvas , Select the painting area on the canvas , We painted blue sky and white clouds in this area , And can continue to write beside the blue sky and white clouds .
about Plotnine for , What it does is a parallel addition , have Step by step Characteristics . This graphical syntax divides the drawing process into data (data)、 mapping (mapping)、 Geometry object (geom)、 Statistical transformation (stats)、 scale (scale)、 Coordinate system (coord)、 Split up (facet) Several parts , The parts are independent of each other . differ Matplotlib, When there is a strong correlation between before and after , Changes often become cumbersome , and Plotnine Just modify the settings of the corresponding part .
It's very much like the process of decorating a statue , Add a garland , Wear a hat , But it's just as easy to remove the wreath and hat from the statue , Especially the style theme (theme) Selection of , Make style adjustment more convenient .
Plot function
about Matplotlib Come on , The drawing function is called matplotlib.pyplot, It is generally recorded as plt; about Plotnine for , yes ggplot. Make good use of these two basic functions , Then find the type of chart we need to draw , Can complete the basic drawing task . Take an example , For example, we now have such a set of data , To draw a histogram :
median_age_dict = {
'coutry': ['New Zealand', 'Spain', 'Ireland', 'Israel', 'Denmark', 'Norway', 'Netherlands', 'Australia', 'Italy', 'Sweden'],
'age': [39.0, 37.0, 35.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0]
}
plt
import matplotlib.pyplot as plt
import pandas as pd
median_age_dict = {
'country': ['New Zealand', 'Spain', 'Ireland', 'Israel', 'Denmark', 'Norway', 'Netherlands', 'Australia', 'Italy',
'Sweden'],
'age': [39.0, 37.0, 35.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0]
}
median_age = pd.DataFrame(median_age_dict)
# Create a form
plt.figure('matplotlib')
# mapping
plt.bar(median_age['country'],median_age['age'])
# Exhibition
plt.show()

ggplot
from plotnine import *
import pandas as pd
median_age_dict = {
'country': ['New Zealand', 'Spain', 'Ireland', 'Israel', 'Denmark', 'Norway', 'Netherlands', 'Australia', 'Italy',
'Sweden'],
'age': [39.0, 37.0, 35.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0]
}
median_age = pd.DataFrame(median_age_dict)
# mapping , a fly in the ointment , No Chinese support
sep = (ggplot(median_age,aes('country','age',fill='country'))+
# Two dimensional bar chart
geom_col()
)
# Exhibition
print(sep)

I can see you ,ggplot The drawing style of is more bright , When directly displayed, the elements of drawing display are more abundant , and plt Is more regular , It belongs to the state that what is added can be displayed , The legend and axis names are not actively displayed .
Common sense of style diversity
Master the histogram 、 Drawing of curve and scatter diagram , Know how to adjust the legend and coordinate axis , Able to adjust line type and point type , And can complete the specified form of image saving , It can basically meet the needs of drawing in daily learning . You can specify separately when you are free in the future .
about Matplotlib Learning from , matplotlib Official website The above information is sufficient , There are also many detailed information among the people , Such as Matplotlib course , Its grammar and Matlab The approximate , Therefore, it can also be used with Matlab Analogical transfer of the use of functions in .
about Plotnine Learning from ,《python The beauty of data visualization 》 A good example map is provided , It is shown below . You can also refer to R Linguistic ggplot2 To learn grammar , There is also a lot of folk information about this , Such as ggplot2 Efficient and practical guide .
Plotnine Learning manual



Matplotlib Simulated dynamic forest fire
Finally, I will show you two more complex examples that I have done , The first is an example of Simulating Forest Dynamic fire , use Matplotlib Draw a dynamic display of the evolution of the square .
#Here we have a 2-D battle field
#One side is green, the other is blue
import matplotlib.animation as animation # Save animation
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
import random
#define class cell
class Cell:
def __init__(self,HP,GEN,site):
self.HP = HP
#self.POS = POS
self.GEN = GEN
self.site = site
#The LOS caused by the enemies
def Attack(self):
LOS = random.uniform(2, 4)
return LOS
#The CURE provided by the teammates
def Heal(self):
CURE = random.uniform(1,3)
return CURE
#Judge if the cell is dead
def Sign(self):
if self.HP <= 0:
return True
else:
return False
#create the cell list
def create_cells(Num,HP):
# the list of sites
sites = []
for j in range(int(np.sqrt(Num))):
for k in range(int(np.sqrt(Num))):
sites.append([j, k])
random.shuffle(sites)
# The amounts of green cells
Green = random.randint(int(np.fix(np.sqrt(Num))), Num)
cells = []
for i in range(0, Green):
cells.append(Cell(HP[0], 'green', sites[i]))
for i in range(Green, Num):
cells.append(Cell(HP[1], 'blue', sites[i]))
return cells
#the battle between two cells
def battle(Cell_1,Cell_2):
if Cell_1.GEN == Cell_2.GEN:
Cell_1.HP += Cell_2.Heal()
Cell_2.HP += Cell_1.Heal()
else:
Cell_1.HP -= Cell_2.Attack()
Cell_2.HP -= Cell_1.Attack()
return [Cell_1.HP,Cell_2.HP]
#the war between the cells
def war(cells):
# for i in range(len(cells)):
# HP = battle(cells[i-1], cells[i])
# cells[i-1].HP = HP[0]
# cells[i].HP = HP[1]
Num = len(cells)
Grid = int(np.sqrt(Num))
for cell_1 in cells:
for cell_2 in cells:
if cell_1.site[1] == cell_2.site[1]:
if cell_1.site[0] == 0:
if cell_2.site[0] == 1 or cell_2.site[0] == Grid:
HP = battle(cell_1, cell_2)
cell_1.HP = HP[0]
cell_2.HP = HP[1]
elif cell_1.site[0] == Grid:
if cell_2.site[0] == 0 or cell_2.site[0] == Grid - 1:
HP = battle(cell_1, cell_2)
cell_1.HP = HP[0]
cell_2.HP = HP[1]
else:
if cell_2.site[0] == cell_1.site[1] - 1 or cell_2.site[0] == cell_1.site[1] + 1:
HP = battle(cell_1, cell_2)
cell_1.HP = HP[0]
cell_2.HP = HP[1]
elif cell_1.site[0] == cell_2.site[0]:
if cell_1.site[1] == 0:
if cell_2.site[1] == 1 or cell_2.site[1] == Grid:
HP = battle(cell_1, cell_2)
cell_1.HP = HP[0]
cell_2.HP = HP[1]
elif cell_1.site[1] == Grid:
if cell_2.site[1] == 0 or cell_2.site[1] == Grid - 1:
HP = battle(cell_1, cell_2)
cell_1.HP = HP[0]
cell_2.HP = HP[1]
else:
if cell_2.site[1] == cell_1.site[1] - 1 or cell_2.site[1] == cell_1.site[1] + 1:
HP = battle(cell_1, cell_2)
cell_1.HP = HP[0]
cell_2.HP = HP[1]
return cells
# visual the war
def visual(cells,ims):
ax = plt.subplot(111)
plt.ion()
reddead = 0
greenlive = 0
bluelive = 0
# get the color
for cell in cells:
x = np.linspace(cell.site[0], cell.site[0] + 1)
if cell.Sign():
ax.fill_between(x, cell.site[1], cell.site[1] + 1, facecolor='red')
reddead += 1
else:
if cell.GEN == 'green':
ax.fill_between(x, cell.site[1], cell.site[1] + 1, facecolor='green')
greenlive += 1
elif cell.GEN == 'blue':
ax.fill_between(x, cell.site[1], cell.site[1] + 1, facecolor='blue')
bluelive += 1
# set the scale
plt.xlim(0, np.sqrt(len(cells)))
plt.ylim(0, np.sqrt(len(cells)))
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.grid(True, which='major') # major,color='black'
ax.yaxis.grid(True, which='major') # major,color='black'
plt.pause(0.8)
ims.append(ax.findobj())
# print([reddead, greenlive, bluelive])
return [reddead, greenlive, bluelive]
def simulata(cells):
fig = plt.figure()
ims = []
initial = visual(cells,ims)
state = [initial]
i = 0
while state[i][0] < initial[1] and state[i][0] < initial[2]:
cells = war(cells)
state.append(visual(cells, ims))
i +=1
ani = animation.ArtistAnimation(fig, ims, interval=500, repeat_delay=1000)
ani.save("test.gif", writer='pillow')
return state
# Here we have a try, assume that we have Num cells
Num = 256
cells = create_cells(Num,[10,10])
state = simulata(cells)
print('Below is the result of simulation:\n',state)
greenlive_ratio = state[-1][1]/state[0][1]
bluelive_ratio = state[-1][2]/state[0][2]
print('\ngreenlive ratio is ',state[-1][1],'/',state[0][1], greenlive_ratio,
'\nbluelive ratio is',state[-1][2],'/',state[0][2],bluelive_ratio)
The effect display is a moving picture , And by the matplotlib.animation Save the dynamic diagram .
Plotnine Point line diagram
The other is to use Plotnine A plot of a set of data , At this time, you can see that the whole style is compact and elegant .
import numpy as np
from plotnine import *
import pandas as pd
def pit():
# data
df = {
'x': [], 'y': [], 'label': []}
y1 = [25978.40, 25978.40, 25978.40, 25978.40, 25978.40, 25978.40,
25978.40, 25978.40, 25978.40, 25978.40, 25978.40]
y2 = [12511.43, 12511.43, 12511.43, 12511.43, 12511.43, 11440.20,
10368.96, 14418.96, 18468.96, 24969.96, 31470.96]
y3 = [47111.58, 47111.58, 47111.58, 46111.58, 45111.58, 42602.52,
40093.45, 35093.45, 30093.45, 27264.94, 24436.42]
y4 = [7055.95, 7055.95, 7055.95, 7555.95, 8055.95, 9550.86,
11045.76, 8074.72, 5103.67, 4645.83, 4187.98]
y5 = [86468.18, 86468.18, 86468.18, 86968.18, 87468.18, 89553.58,
91638.97, 95560.02, 99481.06, 96266.42, 93051.78]
Num = 11
for i in range(Num):
df['x'].append(i + 1)
df['y'].append(y1[i])
df['label'].append('CO')
for i in range(Num):
df['x'].append(i + 1)
df['y'].append(y2[i])
df['label'].append('WY')
for i in range(Num):
df['x'].append(i + 1)
df['y'].append(y3[i])
df['label'].append('AZ')
for i in range(Num):
df['x'].append(i + 1)
df['y'].append(y4[i])
df['label'].append('NM')
for i in range(Num):
df['x'].append(i + 1)
df['y'].append(y5[i])
df['label'].append('CA')
cases = ['(0,1)', '(0.2,0.8)', '(0.4,0.6)', '(0.6,0.4)', '(0.8,0.2)', '(1,0)']
df = pd.DataFrame(df)
COLOR = ('#F91400', '#FF328E')
SHAPE = ('o', 's')
# mapping
first_plot = (ggplot(df, aes('x', 'y', shape='label', fill='label', color='label')) +
# Combination of dot line diagram
geom_point(size=3) +
geom_line(size=1) +
labs(x=' ', y="", title=' ') +
# Axis adjustment
scale_x_continuous(limits=(0, 11), breaks=np.linspace(1, 11, 6), labels=cases) +
# Style adjustment , This is a very convenient and flexible step
theme_bw(
)
)
first_plot.save('alplan.png', width=10, height=4.5)
print(first_plot)
pit()

边栏推荐
- 光谱共焦如何测量玻璃基板厚度
- Custom jsp[if, foreach, data, select] tag
- Batch generate folders based on file names
- Review the old and know the new -- constant renewal at normal temperature
- memcached基础5
- 统计无向图中无法互相到达点对数[经典建邻接表+DFS统计 -> 并查集优化][并查集手册/写的详细]
- 基于SSMP的宠物医院管理系统
- LeetCode 142. 环形链表 II
- Moher College -x-forwarded-for injection vulnerability practice
- memcached基础7
猜你喜欢

Buuctf PWN write UPS (6)

如何把老式键盘转换成USB键盘并且自己编程?

Esp32 experiment - self built web server distribution network 02

Moher College - SQL injection vulnerability test (error reporting and blind note)

flutter系列之:flutter中的flow

About Random Numbers

Sword finger offer 10- ii Frog jumping on steps

ESP32-添加多目录的自定义组件

2022年地理信息系统与遥感专业就业前景与升学高校排名选择

2022年地理信息系统与遥感专业就业前景与升学高校排名选择
随机推荐
Statistical Hypothesis Testing
3-wire SPI screen driving mode
Find the minimum value in the rotation sort array ii[classical Abstract dichotomy + how to break the game left, middle and right are equal]
记录一次换行符引起的bug
Database interview questions +sql statement analysis
Keepalived 实现 Redis AutoFailover (RedisHA)16
2022年地理信息系统与遥感专业就业前景与升学高校排名选择
From bitmap to bloom filter, C # implementation
memcached基础6
3 - wire SPI Screen Drive
Redis detailed tutorial
MATLAB data type - character type
Xiaobai looks at MySQL -- installing MySQL in Windows Environment
In depth understanding of UDP in the transport layer and the use of UDP in sockets
Lwip之定时机制
Solve the problem that stc8g1k08 program cannot run and port configuration
What is the difference between the working principle of gas-liquid slip ring and other slip rings
Reading graph augmentations to learn graph representations (lg2ar)
XML learning notes
Skills needing attention in selection and purchase of slip ring