要进行绘图方面的编程,首先要有关于绘图的包,原装的python一般不带有这个包,所以需要自己额外下载。网上看了很多教程,但是都无法成功下载,自己误打误撞安装成功了,给读者安利一下。
首先打开pycharm,file–>settings,然后如图所示

在搜索框内搜索matplotlib,点击下方的install package即可,如果还不能成功import,再重新打开一次idle即可。至此,绘图的matplotlib包就安装好啦。

matplotlib初体验,绘制简单折线图
import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
plt.plot(squares)
plt.show()
标签和线条粗细
squares = [1,4,9,16,25]
plt.plot(squares,linewidth = 5)
# 设置标题,坐标并加上标签
plt.title("Square Numbers",fontsize = 24)
plt.xlabel("Value",fontsize = 14)
plt.ylabel("Square of value",fontsize = 14)
plt.tick_params(axis='both',labelsize = 14)
plt.show()

校正图形,给横坐标也进行指定,使用scatter函数
xvalues = [1,2,3,4,5]
plt.plot(xvalues,squares,linewidth = 5)
plt.scatter(xvalues,squares,s = 100)
plt.show()
随机漫步图(后面附带结果图)
from random import choice
class RandomWalk():
def __init__(self,num_points = 5000):
self.num_points = num_points
# 所有的随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
# 不断漫步,直至到达指定的长度
while len(self.x_values) < self.num_points:
# 决定前进方向以及沿这个方向前进的距离
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
# 拒绝原地踏步
if x_step == 0 and y_step == 0:
continue
# 计算下一个点的x和y值
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
while True:
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
keep_running = input("Make another walk?(y/n):")
if(keep_running == 'n'):
break

安装的过程参看第一节matplotlib的步骤即可
python 的 可视化包pygal可以生成可缩放的矢量图形文件,且支持在线的方式使用图表,结果也很美观。
接下来对多次投掷骰子的结果进行统计,并运用pygal来进行可视化(注意参看代码注释便于理解)
from random import randint
import pygal
class Die():
# 建立一个骰子类
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
return randint(1, self.num_sides)
# 创建对象,掷骰子
die = Die()
results = []
for roll_num in range(100):
result = die.roll()
results.append(result)
print(results)
# 分析结果
frequencies = []
for value in range(1,die.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
# 对结果进行可视化
hist = pygal.Bar()
hist.title = "Results of rolling 100 times in Die"
hist.x_labels = ['1','2','3','4','5','6']
hist.x_title = "Result"
hist._y_title = "Frequency of result"
hist.add('D6',frequencies)
hist.render_to_file('die_visual.svg')

结果美观到爆炸,比直接用matplotlib或者excel进行简单统计画图好多了。