当前位置:网站首页>Data visualization
Data visualization
2022-07-27 10:11:00 【Morbidmuse】
Data visualization
# Draw a simple line chart
import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
# Draw one or more charts in a picture
fig,ax = plt.subplots()
# print(fig,ax)
# >>>Figure(640x480) AxesSubplot(0.125,0.11;0.775x0.77)
# According to Chinese
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
# Charting
ax.plot(squares,linewidth=3) # linewidth Set the line thickness
# Set chart title , Horizontal and vertical axis description
ax.set_title(' Square number ',fontsize=24)
ax.set_xlabel(' value ',fontsize=14)
ax.set_ylabel(' square ',fontsize=14)
# Set the scale mark size
ax.tick_params(axis='both',labelsize=14)
plt.show()

# Correct the figure
# towards plot() Provide a series of hours , It assumes that the first data point corresponds to x Coordinate for 0, This will cause inaccurate graphics
# The solution is to provide both input and output values
# mpl_squares.py
mpl_squares.py
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
# Use built-in styles
plt.style.use('bmh')
fig,ax = plt.subplots()
ax.plot(input_values,squares,linewidth=3)
# Set chart title , Horizontal and vertical axis description
ax.set_title(' Square number ',fontsize=24)
ax.set_xlabel(' value ',fontsize=14)
ax.set_ylabel(' square ',fontsize=14)
# Set the scale mark size
ax.tick_params(axis='both',labelsize=14)
plt.show()

# Use built-in styles
print(plt.style.available)
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
# Use scatter() Draw a scatter plot
# catter_squares.py
catter_squares.py
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.style.use('bmh')
fig,ax = plt.subplots()
ax.scatter(2,4,s=200) # s=200 It refers to the size of the point
ax.set_title(' Square number ',fontsize=24)
ax.set_xlabel(' value ',fontsize=14)
ax.set_ylabel(' square ',fontsize=14)
ax.tick_params(axis='both',which='major',labelsize=14)
plt.show()

# Auto save chart
# plt.savefig(" file name .png",bbox_inches='tight') # bbox_inches='tight' Whether to keep the extra blank area of the chart , Keep it without writing this parameter
# Random walk
""" establish RandomWalk class random_walk.py It randomly chooses the direction of travel Three attributes The variable of the number of random walks Two lists , Store the... Of each point that the random walk passes through separately x Coordinates and y coordinate fill_walk() Method calculate all points that random walk passes """
'\n establish RandomWalk class random_walk.py\n It randomly chooses the direction of travel \n Three attributes \n The variable of the number of random walks \n Two lists , Store the... Of each point that the random walk passes through separately x Coordinates and y coordinate \nfill_walk() Method calculate all points that random walk passes \n'
random_walk.py
from random import choice
class RandomWalk:
""" A class that generates random walk data """
def __init__(self,num_points=5000):
""" Initialize random walk properties """
self.num_points = num_points
# All random walks begin with (0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
""" Calculate all the points included in the random walk """
# Keep walking , Until the list reaches the specified length
while len(self.x_values) <self.num_points:
# Determine the direction and distance to go
x_direction = choice([1,-1])
x_distance = choice([0,1,2,3,4])
x_step = x_direction * x_distance
y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4])
y_step = y_direction * y_distance
# Refuse to step in place
if x_step == 0 and y_step == 0 :
continue
# Calculate the... Of the next point x, and y value
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
# Draw a random walk diagram
# rw_visual.py
rw_visual.py
# Draw a scatter diagram of random walk
import matplotlib.pyplot as plt
from random_walk import RandomWalk
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.style.use('classic')
while True:
rw = RandomWalk(50_000)
rw.fill_walk()
fig,ax = plt.subplots(figsize=(15,9)) # figsize=(15,9) Used to specify dimensions In inches
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values,rw.y_values,c=point_numbers, # Apply color mapping and remove outline colors
cmap=plt.cm.Blues,edgecolors='none',s=1)
# Redraw the start and end points
ax.scatter(0,0,c='green',edgecolors='none',s=100)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
# Hide axis
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# ax.plot(rw.x_values,rw.y_values)
plt.show()
keep_running = input(' Whether or not to continue Y/N?')
if keep_running.lower() == 'n':
break

Whether or not to continue Y/N?n
# Use plotly Simulate rolling dice
# When you need to create a chart displayed in the browser ,Plotly It is useful to ,
# The charts it generates are interactive
# Create a class that represents dice die.py
# Visualization of dice die_visual.py
die.py
from random import randint
class Die:
""" Represents a class of dice """
def __init__(self,num_sides=6):
""" Dice default to 6 Noodles """
self.num_sides = num_sides
def roll(self):
""" Return to one 1, To the random value of the number of dice faces """
return randint(1,self.num_sides)
die_visual.py
from plotly.graph_objs import Bar,Layout
from plotly import offline
from die import Die
# Create a D6
# Simultaneous throw 2 Dice
die_1 = Die()
die_2 = Die(10)
# Roll the dice several times and save the results in a list
results = []
for roll_num in range(10000):
results.append(die_1.roll() + die_2.roll())
# print(results)
max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(x) for x in range(2,max_result+1)]
# print(frequencies)
# print(1/6)
# Visualize the results
x_values = list(range(2,max_result+1))
data = [Bar(x=x_values,y=frequencies)]
x_axis_cofig = {
'title':' result ','dtick':1}
y_axis_cofig = {
'title':' The frequency of the results '}
my_layout=Layout(title=" throw 1 individual D6, One D10 dice 10000 Results of ",
xaxis=x_axis_cofig,yaxis=y_axis_cofig)
offline.plot({
'data':data,'layout' : my_layout}, filename='d6.html')
'd6.html'

ref: 《python Programming from entry to practice 》( The second edition )
边栏推荐
- 吃透Chisel语言.24.Chisel时序电路(四)——Chisel内存(Memory)详解
- 备战金九银十Android面试准备(含面试全流程,面试准备工作面试题和资料等)
- Anaconda installation (very detailed)
- Interview JD T5, was pressed on the ground friction, who knows what I experienced?
- hdu5289(Assignment)
- DCGAN论文改进之处+简化代码
- Shell process control (emphasis), if judgment, case statement, let usage, for ((initial value; loop control condition; variable change)) and for variable in value 1 value 2 value 3..., while loop
- 3D face reconstruction and dense alignment with position map progression network
- There is no CUDA option in vs2019+cuda11.1 new project
- Ant高级-task
猜你喜欢

卸载CUDA11.1

Review of in vivo detection

Understand chisel language. 22. Chisel sequential circuit (II) -- detailed explanation of chisel counter: counter, timer and pulse width modulation

ACL2021最佳论文出炉,来自字节跳动

NFT system development - Tutorial

超赞的卡尔曼滤波详解文章

Interview JD T5, was pressed on the ground friction, who knows what I experienced?

Brush the title "sword finger offer" day03

hdu5288(OO’s Sequence)

Robotframework+eclispe environment installation
随机推荐
数据库性能系列之子查询
Go Basics - arrays and slices
二叉树习题总结
7/26 thinking +dp+ suffix array learning
hdu5288(OO’s Sequence)
Looking for a job for 4 months, interviewing 15 companies and getting 3 offers
TFlite 的简单使用
S交换机堆叠方案配置指南
pillow的原因ImportError: cannot import name ‘PILLOW_VERSION‘ from ‘PIL‘,如何安装pillow<7.0.0
Vs2019 Community Edition Download tutorial (detailed)
Case of burr (bulge) notch (depression) detection of circular workpiece
StyleGAN论文笔记+修改代码尝试3D点云生成
省应急管理厅:广州可争取推广幼儿应急安全宣教经验
直播倒计时 3 天|SOFAChannel#29 基于 P2P 的文件和镜像加速系统 Dragonfly
oracle rac 19c pdb实例当掉
Shell process control (emphasis), if judgment, case statement, let usage, for ((initial value; loop control condition; variable change)) and for variable in value 1 value 2 value 3..., while loop
Understand chisel language. 26. Chisel advanced input signal processing (II) -- majority voter filtering, function abstraction and asynchronous reset
并发之park与unpark说明
吃透Chisel语言.24.Chisel时序电路(四)——Chisel内存(Memory)详解
Shell operator, $((expression)) "or" $[expression], expr method, condition judgment, test condition, [condition], comparison between two integers, judgment according to file permission, judgment accor