当前位置:   article > 正文

python图像代码大全,python编程代码图片_python图形代码大全

python图形代码大全

大家好,小编为大家解答python图像代码大全的问题。很多人还不知道python编程代码图片,现在让我们一起来看看吧!

Python画图

Python常用的绘图工具包括:matplotlib, seaborn, plotly等,以及一些其他专用于绘制某类图如词云图等的包,描绘绘图轨迹的turtle包等。本章节将会使用一些例子由易到难的阐述绘图的经典小例子,目前共收录10python绘制满天星教学设计

1 turtle绘制奥运五环图

turtle绘图的函数非常好用,基本看到函数名字,就能知道它的含义,下面使用turtle,仅用15行代码来绘制奥运五环图。

1 导入库

  1. import turtle
  2. 复制代码

2 定义画圆函数

  1. def drawCircle(x,y,c='red'):
  2. p.pu()# 抬起画笔
  3. p.goto(x,y) # 绘制圆的起始位置
  4. p.pd()# 放下画笔
  5. p.color(c)# 绘制c色圆环
  6. p.circle(30,360) #绘制圆:半径,角度
  7. 复制代码

3 画笔基本设置

  1. p = turtle
  2. p.pensize(3) # 画笔尺寸设置3
  3. 复制代码

4 绘制五环图

调用画圆函数

  1. drawCircle(0,0,'blue')
  2. drawCircle(60,0,'black')
  3. drawCircle(120,0,'red')
  4. drawCircle(90,-30,'green')
  5. drawCircle(30,-30,'yellow')
  6. p.done()
2 turtle绘制漫天雪花

导入模块

导入 turtle库和 python的 random

  1. import turtle as p
  2. import random

绘制雪花

  1. def snow(snow_count):
  2. p.hideturtle()
  3. p.speed(500)
  4. p.pensize(2)
  5. for i in range(snow_count):
  6. r = random.random()
  7. g = random.random()
  8. b = random.random()
  9. p.pencolor(r, g, b)
  10. p.pu()
  11. p.goto(random.randint(-350, 350), random.randint(1, 270))
  12. p.pd()
  13. dens = random.randint(8, 12)
  14. snowsize = random.randint(10, 14)
  15. for _ in range(dens):
  16. p.forward(snowsize) # 向当前画笔方向移动snowsize像素长度
  17. p.backward(snowsize) # 向当前画笔相反方向移动snowsize像素长度
  18. p.right(360 / dens) # 顺时针移动360 / dens度

绘制地面

  1. def ground(ground_line_count):
  2. p.hideturtle()
  3. p.speed(500)
  4. for i in range(ground_line_count):
  5. p.pensize(random.randint(5, 10))
  6. x = random.randint(-400, 350)
  7. y = random.randint(-280, -1)
  8. r = -y / 280
  9. g = -y / 280
  10. b = -y / 280
  11. p.pencolor(r, g, b)
  12. p.penup() # 抬起画笔
  13. p.goto(x, y) # 让画笔移动到此位置
  14. p.pendown() # 放下画笔
  15. p.forward(random.randint(40, 100)) # 眼当前画笔方向向前移动40~100距离

主函数

  1. def main():
  2. p.setup(800, 600, 0, 0)
  3. # p.tracer(False)
  4. p.bgcolor("black")
  5. snow(30)
  6. ground(30)
  7. # p.tracer(True)
  8. p.mainloop()
  9. main()
3 wordcloud词云图
  1. import hashlib
  2. import pandas as pd
  3. from wordcloud import WordCloud
  4. geo_data=pd.read_excel(r"../data/geo_data.xlsx")
  5. print(geo_data)
  6. # 0 深圳
  7. # 1 深圳
  8. # 2 深圳
  9. # 3 深圳
  10. # 4 深圳
  11. # 5 深圳
  12. # 6 深圳
  13. # 7 广州
  14. # 8 广州
  15. # 9 广州
  16. words = ','.join(x for x in geo_data['city'] if x != []) #筛选出非空列表值
  17. wc = WordCloud(
  18. background_color="green", #背景颜色"green"绿色
  19. max_words=100, #显示最大词数
  20. font_path='./fonts/simhei.ttf', #显示中文
  21. min_font_size=5,
  22. max_font_size=100,
  23. width=500 #图幅宽度
  24. )
  25. x = wc.generate(words)
  26. x.to_file('../data/geo_data.png')
  27. 复制代码

[图片上传失败...(image-78330d-1577689175382)]

4 plotly画柱状图和折线图
  1. #柱状图+折线图
  2. import plotly.graph_objects as go
  3. fig = go.Figure()
  4. fig.add_trace(
  5. go.Scatter(
  6. x=[0, 1, 2, 3, 4, 5],
  7. y=[1.5, 1, 1.3, 0.7, 0.8, 0.9]
  8. ))
  9. fig.add_trace(
  10. go.Bar(
  11. x=[0, 1, 2, 3, 4, 5],
  12. y=[2, 0.5, 0.7, -1.2, 0.3, 0.4]
  13. ))
  14. fig.show()
5 seaborn热力图
  1. # 导入库
  2. import seaborn as sns
  3. import pandas as pd
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. # 生成数据集
  7. data = np.random.random((6,6))
  8. np.fill_diagonal(data,np.ones(6))
  9. features = ["prop1","prop2","prop3","prop4","prop5", "prop6"]
  10. data = pd.DataFrame(data, index = features, columns=features)
  11. print(data)
  12. # 绘制热力图
  13. heatmap_plot = sns.heatmap(data, center=0, cmap='gist_rainbow')
  14. plt.show()
 
6 matplotlib折线图

模块名称:example_utils.py,里面包括三个函数,各自功能如下:

  1. import matplotlib.pyplot as plt
  2. # 创建画图fig和axes
  3. def setup_axes():
  4. fig, axes = plt.subplots(ncols=3, figsize=(6.5,3))
  5. for ax in fig.axes:
  6. ax.set(xticks=[], yticks=[])
  7. fig.subplots_adjust(wspace=0, left=0, right=0.93)
  8. return fig, axes
  9. # 图片标题
  10. def title(fig, text, y=0.9):
  11. fig.suptitle(text, size=14, y=y, weight='semibold', x=0.98, ha='right',
  12. bbox=dict(boxstyle='round', fc='floralwhite', ec='#8B7E66',
  13. lw=2))
  14. # 为数据添加文本注释
  15. def label(ax, text, y=0):
  16. ax.annotate(text, xy=(0.5, 0.00), xycoords='axes fraction', ha='center',
  17. style='italic',
  18. bbox=dict(boxstyle='round', facecolor='floralwhite',
  19. ec='#8B7E66'))
 
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import example_utils
  4. x = np.linspace(0, 10, 100)
  5. fig, axes = example_utils.setup_axes()
  6. for ax in axes:
  7. ax.margins(y=0.10)
  8. # 子图1 默认plot多条线,颜色系统分配
  9. for i in range(1, 6):
  10. axes[0].plot(x, i * x)
  11. # 子图2 展示线的不同linestyle
  12. for i, ls in enumerate(['-', '--', ':', '-.']):
  13. axes[1].plot(x, np.cos(x) + i, linestyle=ls)
  14. # 子图3 展示线的不同linestyle和marker
  15. for i, (ls, mk) in enumerate(zip(['', '-', ':'], ['o', '^', 's'])):
  16. axes[2].plot(x, np.cos(x) + i * x, linestyle=ls, marker=mk, markevery=10)
  17. # 设置标题
  18. # example_utils.title(fig, '"ax.plot(x, y, ...)": Lines and/or markers', y=0.95)
  19. # 保存图片
  20. fig.savefig('plot_example.png', facecolor='none')
  21. # 展示图片
  22. plt.show()
  23. 复制代码
7 matplotlib散点图

对应代码:

  1. """
  2. 散点图的基本用法
  3. """
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. import example_utils
  7. # 随机生成数据
  8. np.random.seed(1874)
  9. x, y, z = np.random.normal(0, 1, (3, 100))
  10. t = np.arctan2(y, x)
  11. size = 50 * np.cos(2 * t)**2 + 10
  12. fig, axes = example_utils.setup_axes()
  13. # 子图1
  14. axes[0].scatter(x, y, marker='o', color='darkblue', facecolor='white', s=80)
  15. example_utils.label(axes[0], 'scatter(x, y)')
  16. # 子图2
  17. axes[1].scatter(x, y, marker='s', color='darkblue', s=size)
  18. example_utils.label(axes[1], 'scatter(x, y, s)')
  19. # 子图3
  20. axes[2].scatter(x, y, s=size, c=z, cmap='gist_ncar')
  21. example_utils.label(axes[2], 'scatter(x, y, s, c)')
  22. # example_utils.title(fig, '"ax.scatter(...)": Colored/scaled markers',
  23. # y=0.95)
  24. fig.savefig('scatter_example.png', facecolor='none')
  25. plt.show()
8 matplotlib柱状图
 

对应代码:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import example_utils
  4. def main():
  5. fig, axes = example_utils.setup_axes()
  6. basic_bar(axes[0])
  7. tornado(axes[1])
  8. general(axes[2])
  9. # example_utils.title(fig, '"ax.bar(...)": Plot rectangles')
  10. fig.savefig('bar_example.png', facecolor='none')
  11. plt.show()
  12. # 子图1
  13. def basic_bar(ax):
  14. y = [1, 3, 4, 5.5, 3, 2]
  15. err = [0.2, 1, 2.5, 1, 1, 0.5]
  16. x = np.arange(len(y))
  17. ax.bar(x, y, yerr=err, color='lightblue', ecolor='black')
  18. ax.margins(0.05)
  19. ax.set_ylim(bottom=0)
  20. example_utils.label(ax, 'bar(x, y, yerr=e)')
  21. # 子图2
  22. def tornado(ax):
  23. y = np.arange(8)
  24. x1 = y + np.random.random(8) + 1
  25. x2 = y + 3 * np.random.random(8) + 1
  26. ax.barh(y, x1, color='lightblue')
  27. ax.barh(y, -x2, color='salmon')
  28. ax.margins(0.15)
  29. example_utils.label(ax, 'barh(x, y)')
  30. # 子图3
  31. def general(ax):
  32. num = 10
  33. left = np.random.randint(0, 10, num)
  34. bottom = np.random.randint(0, 10, num)
  35. width = np.random.random(num) + 0.5
  36. height = np.random.random(num) + 0.5
  37. ax.bar(left, height, width, bottom, color='salmon')
  38. ax.margins(0.15)
  39. example_utils.label(ax, 'bar(l, h, w, b)')
  40. main()
9 matplotlib等高线图

对应代码:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from matplotlib.cbook import get_sample_data
  4. import example_utils
  5. z = np.load(get_sample_data('bivariate_normal.npy'))
  6. fig, axes = example_utils.setup_axes()
  7. axes[0].contour(z, cmap='gist_earth')
  8. example_utils.label(axes[0], 'contour')
  9. axes[1].contourf(z, cmap='gist_earth')
  10. example_utils.label(axes[1], 'contourf')
  11. axes[2].contourf(z, cmap='gist_earth')
  12. cont = axes[2].contour(z, colors='black')
  13. axes[2].clabel(cont, fontsize=6)
  14. example_utils.label(axes[2], 'contourf + contour\n + clabel')
  15. # example_utils.title(fig, '"contour, contourf, clabel": Contour/label 2D data',
  16. # y=0.96)
  17. fig.savefig('contour_example.png', facecolor='none')
  18. plt.show()
10 imshow图
 

对应代码:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from matplotlib.cbook import get_sample_data
  4. from mpl_toolkits import axes_grid1
  5. import example_utils
  6. def main():
  7. fig, axes = setup_axes()
  8. plot(axes, *load_data())
  9. # example_utils.title(fig, '"ax.imshow(data, ...)": Colormapped or RGB arrays')
  10. fig.savefig('imshow_example.png', facecolor='none')
  11. plt.show()
  12. def plot(axes, img_data, scalar_data, ny):
  13. # 默认线性插值
  14. axes[0].imshow(scalar_data, cmap='gist_earth', extent=[0, ny, ny, 0])
  15. # 最近邻插值
  16. axes[1].imshow(scalar_data, cmap='gist_earth', interpolation='nearest',
  17. extent=[0, ny, ny, 0])
  18. # 展示RGB/RGBA数据
  19. axes[2].imshow(img_data)
  20. def load_data():
  21. img_data = plt.imread(get_sample_data('5.png'))
  22. ny, nx, nbands = img_data.shape
  23. scalar_data = np.load(get_sample_data('bivariate_normal.npy'))
  24. return img_data, scalar_data, ny
  25. def setup_axes():
  26. fig = plt.figure(figsize=(6, 3))
  27. axes = axes_grid1.ImageGrid(fig, [0, 0, .93, 1], (1, 3), axes_pad=0)
  28. for ax in axes:
  29. ax.set(xticks=[], yticks=[])
  30. return fig, axes
  31. main()
  32. 复制代码
11 pyecharts绘制仪表盘

使用pip install pyecharts 安装,版本为 v1.6,pyecharts绘制仪表盘,只需要几行代码:

  1. from pyecharts import charts
  2. # 仪表盘
  3. gauge = charts.Gauge()
  4. gauge.add('Python小例子', [('Python机器学习', 30), ('Python基础', 70.),
  5. ('Python正则', 90)])
  6. gauge.render(path="./data/仪表盘.html")
  7. print('ok')

仪表盘中共展示三项,每项的比例为30%,70%,90%,如下图默认名称显示第一项:Python机器学习,完成比例为30%

 
12 pyecharts漏斗图
  1. from pyecharts import options as opts
  2. from pyecharts.charts import Funnel, Page
  3. from random import randint
  4. def funnel_base() -> Funnel:
  5. c = (
  6. Funnel()
  7. .add("豪车", [list(z) for z in zip(['宝马', '法拉利', '奔驰', '奥迪', '大众', '丰田', '特斯拉'],
  8. [randint(1, 20) for _ in range(7)])])
  9. .set_global_opts(title_opts=opts.TitleOpts(title="豪车漏斗图"))
  10. )
  11. return c
  12. funnel_base().render('./img/car_fnnel.html')
  13. 复制代码

以7种车型及某个属性值绘制的漏斗图,属性值大越靠近漏斗的大端。

 
13 pyecharts日历图
  1. import datetime
  2. import random
  3. from pyecharts import options as opts
  4. from pyecharts.charts import Calendar
  5. def calendar_interval_1() -> Calendar:
  6. begin = datetime.date(2019, 1, 1)
  7. end = datetime.date(2019, 12, 27)
  8. data = [
  9. [str(begin + datetime.timedelta(days=i)), random.randint(1000, 25000)]
  10. for i in range(0, (end - begin).days + 1, 2) # 隔天统计
  11. ]
  12. calendar = (
  13. Calendar(init_opts=opts.InitOpts(width="1200px")).add(
  14. "", data, calendar_opts=opts.CalendarOpts(range_="2019"))
  15. .set_global_opts(
  16. title_opts=opts.TitleOpts(title="Calendar-2019年步数统计"),
  17. visualmap_opts=opts.VisualMapOpts(
  18. max_=25000,
  19. min_=1000,
  20. orient="horizontal",
  21. is_piecewise=True,
  22. pos_top="230px",
  23. pos_left="100px",
  24. ),
  25. )
  26. )
  27. return calendar
  28. calendar_interval_1().render('./img/calendar.html')
  29. 复制代码

绘制2019年1月1日到12月27日的步行数,官方给出的图形宽度900px不够,只能显示到9月份,本例使用opts.InitOpts(width="1200px")做出微调,并且visualmap显示所有步数,每隔一天显示一次:

 
14 pyecharts绘制graph图
  1. import json
  2. import os
  3. from pyecharts import options as opts
  4. from pyecharts.charts import Graph, Page
  5. def graph_base() -> Graph:
  6. nodes = [
  7. {"name": "cus1", "symbolSize": 10},
  8. {"name": "cus2", "symbolSize": 30},
  9. {"name": "cus3", "symbolSize": 20}
  10. ]
  11. links = []
  12. for i in nodes:
  13. if i.get('name') == 'cus1':
  14. continue
  15. for j in nodes:
  16. if j.get('name') == 'cus1':
  17. continue
  18. links.append({"source": i.get("name"), "target": j.get("name")})
  19. c = (
  20. Graph()
  21. .add("", nodes, links, repulsion=8000)
  22. .set_global_opts(title_opts=opts.TitleOpts(title="customer-influence"))
  23. )
  24. return c

构建图,其中客户点1与其他两个客户都没有关系(link),也就是不存在有效边:

 
15 pyecharts水球图
  1. from pyecharts import options as opts
  2. from pyecharts.charts import Liquid, Page
  3. from pyecharts.globals import SymbolType
  4. def liquid() -> Liquid:
  5. c = (
  6. Liquid()
  7. .add("lq", [0.67, 0.30, 0.15])
  8. .set_global_opts(title_opts=opts.TitleOpts(title="Liquid"))
  9. )
  10. return c
  11. liquid().render('./img/liquid.html')

水球图的取值[0.67, 0.30, 0.15]表示下图中的三个波浪线,一般代表三个百分比:

 
16 pyecharts饼图
  1. from pyecharts import options as opts
  2. from pyecharts.charts import Pie
  3. from random import randint
  4. def pie_base() -> Pie:
  5. c = (
  6. Pie()
  7. .add("", [list(z) for z in zip(['宝马', '法拉利', '奔驰', '奥迪', '大众', '丰田', '特斯拉'],
  8. [randint(1, 20) for _ in range(7)])])
  9. .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例"))
  10. .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
  11. )
  12. return c
  13. pie_base().render('./img/pie_pyecharts.html')
 
17 pyecharts极坐标图
  1. import random
  2. from pyecharts import options as opts
  3. from pyecharts.charts import Page, Polar
  4. def polar_scatter0() -> Polar:
  5. data = [(alpha, random.randint(1, 100)) for alpha in range(101)] # r = random.randint(1, 100)
  6. print(data)
  7. c = (
  8. Polar()
  9. .add("", data, type_="bar", label_opts=opts.LabelOpts(is_show=False))
  10. .set_global_opts(title_opts=opts.TitleOpts(title="Polar"))
  11. )
  12. return c
  13. polar_scatter0().render('./img/polar.html')

极坐标表示为(夹角,半径),如(6,94)表示夹角为6,半径94的点:

 
18 pyecharts词云图
  1. from pyecharts import options as opts
  2. from pyecharts.charts import Page, WordCloud
  3. from pyecharts.globals import SymbolType
  4. words = [
  5. ("Python", 100),
  6. ("C++", 80),
  7. ("Java", 95),
  8. ("R", 50),
  9. ("JavaScript", 79),
  10. ("C", 65)
  11. ]
  12. def wordcloud() -> WordCloud:
  13. c = (
  14. WordCloud()
  15. # word_size_range: 单词字体大小范围
  16. .add("", words, word_size_range=[20, 100], shape='cardioid')
  17. .set_global_opts(title_opts=opts.TitleOpts(title="WordCloud"))
  18. )
  19. return c
  20. wordcloud().render('./img/wordcloud.html')

("C",65)表示在本次统计中C语言出现65次

19 pyecharts系列柱状图
  1. from pyecharts import options as opts
  2. from pyecharts.charts import Bar
  3. from random import randint
  4. def bar_series() -> Bar:
  5. c = (
  6. Bar()
  7. .add_xaxis(['宝马', '法拉利', '奔驰', '奥迪', '大众', '丰田', '特斯拉'])
  8. .add_yaxis("销量", [randint(1, 20) for _ in range(7)])
  9. .add_yaxis("产量", [randint(1, 20) for _ in range(7)])
  10. .set_global_opts(title_opts=opts.TitleOpts(title="Bar的主标题", subtitle="Bar的副标题"))
  11. )
  12. return c
  13. bar_series().render('./img/bar_series.html')
  14. 复制代码
20 pyecharts热力图
  1. import random
  2. from pyecharts import options as opts
  3. from pyecharts.charts import HeatMap
  4. def heatmap_car() -> HeatMap:
  5. x = ['宝马', '法拉利', '奔驰', '奥迪', '大众', '丰田', '特斯拉']
  6. y = ['中国','日本','南非','澳大利亚','阿根廷','阿尔及利亚','法国','意大利','加拿大']
  7. value = [[i, j, random.randint(0, 100)]
  8. for i in range(len(x)) for j in range(len(y))]
  9. c = (
  10. HeatMap()
  11. .add_xaxis(x)
  12. .add_yaxis("销量", y, value)
  13. .set_global_opts(
  14. title_opts=opts.TitleOpts(title="HeatMap"),
  15. visualmap_opts=opts.VisualMapOpts(),
  16. )
  17. )
  18. return c
  19. heatmap_car().render('./img/heatmap_pyecharts.html')

热力图描述的实际是三维关系,x轴表示车型,y轴表示国家,每个色块的颜色值代表销量,颜色刻度尺显示在左下角,颜色越红表示销量越大。

文章知识点与官方知识档案匹配,可进一步学习相关知识
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/994235
推荐阅读
相关标签
  

闽ICP备14008679号