记录维维的每一篇Hello World

10.jpg

导入工具包

  1. import matplotlib.pyplot as plt

基础使用

折线图

  1. import matplotlib.pyplot as plt
  2. # x的值
  3. x = [0, 1, 2, 3]
  4. # y的值
  5. y = [0, 3, 2, 7]
  6. # 画图
  7. plt.plot(x, y)
  8. # 显示
  9. plt.show()

散点图

  1. import matplotlib.pyplot as plt
  2. # x的值
  3. x = [0, 1, 2, 3]
  4. # y的值
  5. y = [3, 5, 3, 5]
  6. # 画图
  7. plt.scatter(x, y)
  8. # 显示
  9. plt.show()

柱状图

  1. import matplotlib.pyplot as plt
  2. # x的标签
  3. x_text = ['one', 'two', 'three']
  4. # x对应的值
  5. x_data = [3, 7, 5]
  6. # 画图
  7. plt.bar(x, data)
  8. # 显示
  9. plt.show()

饼图

  1. import matplotlib.pyplot as plt
  2. # 每块对应的值
  3. val = [3, 4, 7]
  4. # 画图
  5. plt.pie(val)
  6. # 显示
  7. plt.show()

直方图

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 400个正态分布的随机数
  4. data = np.random.normal(100, 15, 400)
  5. # 画图, bins值分50块
  6. plt.hist(data, bins=50)
  7. #显示
  8. plt.show()

热力图

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 5×5的随机数矩阵
  4. data = np.random.random((5, 5))
  5. # 画图
  6. plt.imshow(data, cmap=plt.cm.hot, vmin=0, vmax=1)
  7. # 颜色参考
  8. plt.colorbar()
  9. # x的标签
  10. plt.xticks(np.arange(5), ['one', 'two', 'three', 'four', 'five'])
  11. # y的标签
  12. plt.yticks(np.arange(5), ['one', 'two', 'three', 'four', 'five'])
  13. # 显示
  14. plt.show()

简单应用

男女每个身高阶段的体重的折线分布

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. import warnings
  5. warnings.filterwarnings("ignore")
  6. plt.rcParams['font.sans-serif'] = ['SimHei']
  7. plt.title(u"身高-体重", c='purple')
  8. file_path = 'E:\\Data\\身高-体重\\500\\500_Person_Gender_Height_Weight_Index.csv'
  9. data_HW = pd.read_csv(file_path)
  10. data_val = data_HW.values
  11. header = data_HW.columns
  12. head_name = data_HW[header[0]].unique()
  13. head_val0 = np.where(data_val == head_name[0])[0]
  14. head_val1 = np.where(data_val == head_name[1])[0]
  15. data_val = data_val.reshape(1, -1)[0]
  16. height_key = np.arange(150, 190, 5)
  17. plt.xticks(height_key, list(map(lambda a, b: f'{a}/{b}', height_key, height_key+5)))
  18. # 女性数据
  19. key = head_val0*4
  20. height0 = data_val[key+1]
  21. weight0 = data_val[key+2]
  22. weight0_mean = list(map(lambda i: weight0[np.where((height0 < i+5) & (height0 >= i))[0]].mean(), height_key))
  23. plt.plot(height_key, weight0_mean, 'r-o', label=u"女孩子")
  24. # 男性的数据
  25. key = head_val1*4
  26. height1 = data_val[key+1]
  27. weight1 = data_val[key+2]
  28. weight1_mean = list(map(lambda i: weight1[np.where((height1 < i+5) & (height1 >= i))[0]].mean(), height_key))
  29. plt.plot(height_key, weight1_mean, 'b-o', label=u"男孩子")
  30. plt.legend()
  31. plt.show()

预览
image.png

男女身高体重的散点分布

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. import warnings
  5. warnings.filterwarnings("ignore")
  6. plt.rcParams['font.sans-serif'] = ['SimHei']
  7. plt.title(u"身高-体重", c='purple')
  8. file_path = 'E:\\Data\\身高-体重\\500\\500_Person_Gender_Height_Weight_Index.csv'
  9. data_HW = pd.read_csv(file_path)
  10. data_val = data_HW.values
  11. header = data_HW.columns
  12. head_name = data_HW[header[0]].unique()
  13. head_val0 = np.where(data_val == head_name[0])[0]
  14. head_val1 = np.where(data_val == head_name[1])[0]
  15. data_val = data_val.reshape(1, -1)[0]
  16. # 女性数据
  17. key = head_val0*4
  18. height0 = data_val[key+1]
  19. weight0 = data_val[key+2]
  20. plt.scatter(height0, weight0, c='red', label=u"女孩子")
  21. # 男性的数据
  22. key = head_val1*4
  23. height1 = data_val[key+1]
  24. weight1 = data_val[key+2]
  25. plt.scatter(height1, weight1, c='blue', label=u"男孩子")
  26. plt.xlabel(u"身高")
  27. plt.ylabel(u"体重")
  28. plt.legend()
  29. plt.show()

预览
image.png

男女每个身高阶段的体重的柱状分布

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. import warnings
  5. warnings.filterwarnings("ignore")
  6. plt.rcParams['font.sans-serif'] = ['SimHei']
  7. plt.title(u"身高-体重", fontdict=dict(size=20, color='purple'))
  8. file_path = 'E:\\Data\\身高-体重\\500\\500_Person_Gender_Height_Weight_Index.csv'
  9. data_HW = pd.read_csv(file_path)
  10. data_val = data_HW.values
  11. header = data_HW.columns
  12. head_name = data_HW[header[0]].unique()
  13. head_val0 = np.where(data_val == head_name[0])[0]
  14. head_val1 = np.where(data_val == head_name[1])[0]
  15. data_val = data_val.reshape(1, -1)[0]
  16. height_key = np.arange(150, 190, 5)
  17. plt.xticks(height_key, list(map(lambda a, b: f'{a}/{b}', height_key, height_key+5)))
  18. # 女性数据
  19. key = head_val0*4
  20. height0 = data_val[key+1]
  21. weight0 = data_val[key+2]
  22. weight0_mean = list(map(lambda i: weight0[np.where((height0 < i+5) & (height0 >= i))[0]].mean(), height_key))
  23. plt.bar(height_key-0.8, weight0_mean, width=1.2, color='r', label=u"女孩子")
  24. # 男性的数据
  25. key = head_val1*4
  26. height1 = data_val[key+1]
  27. weight1 = data_val[key+2]
  28. weight1_mean = list(map(lambda i: weight1[np.where((height1 < i+5) & (height1 >= i))[0]].mean(), height_key))
  29. plt.bar(height_key+0.8, weight1_mean, width=1.2, color='b', label=u"男孩子")
  30. plt.xlabel(u"身高")
  31. plt.ylabel(u"体重")
  32. plt.legend()
  33. plt.show()

预览
image.png

男女每个身高阶段的人数的饼图

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. import warnings
  5. warnings.filterwarnings("ignore")
  6. plt.rcParams['font.sans-serif'] = ['SimHei']
  7. file_path = 'E:\\Data\\身高-体重\\500\\500_Person_Gender_Height_Weight_Index.csv'
  8. data_HW = pd.read_csv(file_path)
  9. data_val = data_HW.values
  10. header = data_HW.columns
  11. head_name = data_HW[header[0]].unique()
  12. head_val0 = np.where(data_val == head_name[0])[0]
  13. head_val1 = np.where(data_val == head_name[1])[0]
  14. data_val = data_val.reshape(1, -1)[0]
  15. plt.figure(figsize=(10, 5), dpi=100)
  16. height_key = np.arange(150, 190, 5)
  17. height_text = list(map(lambda a, b: f'{a}/{b}', height_key, height_key + 5))
  18. # 女性数据
  19. key = head_val0 * 4
  20. height0 = data_val[key + 1]
  21. weight0_mean = list(map(lambda i: np.where((height0 < i + 5) & (height0 >= i))[0].size, height_key))
  22. plt_one = plt.subplot(1, 2, 1)
  23. plt_one.pie(weight0_mean, labels=height_text, autopct="%1.2f%%",
  24. textprops={'fontsize': 16}, labeldistance=1.05,
  25. shadow=True, pctdistance=0.5)
  26. plt.title("女孩子")
  27. # 男性的数据
  28. key = head_val1 * 4
  29. height1 = data_val[key + 1]
  30. weight1_mean = list(map(lambda i: np.where((height1 < i + 5) & (height1 >= i))[0].size, height_key))
  31. plt_two = plt.subplot(1, 2, 2)
  32. plt_two.pie(weight1_mean, labels=height_text, autopct="%1.2f%%",
  33. textprops={'fontsize': 16}, labeldistance=1.05,
  34. shadow=True, pctdistance=0.5)
  35. plt.title("男孩子")
  36. plt.legend()
  37. plt.show()

预览
image.png

绘画动态爱心

  1. import os
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import matplotlib.animation as animation
  5. import warnings
  6. warnings.filterwarnings("ignore")
  7. plt.rcParams['font.sans-serif'] = ['SimHei']
  8. plt.rcParams['axes.unicode_minus'] = False
  9. fig = plt.figure(figsize=(10, 5), dpi=100, facecolor='black')
  10. plt.grid(ls='--', alpha=0.5)
  11. x = np.linspace(-3, 3, 100000)
  12. f = np.sqrt(1 - (np.abs(x) - 1) ** 2)
  13. h = -2 * np.sqrt(1 - 0.5 * np.abs(x))
  14. q = (f - h) / 2 * np.cos(0 * x) + (f + h) / 2
  15. plt.subplot(121, facecolor="black")
  16. plt.xlim(-3, 3)
  17. plt.ylim(-3, 2)
  18. plt.title("love", fontdict=dict(color='r', size=24))
  19. plt_love = plt.plot(x, q, 'r')[0]
  20. plt.subplot(122, facecolor="black")
  21. plt.xlim(-3, 3)
  22. plt.ylim(-3, 2)
  23. plt.title("爱心", fontdict=dict(color='r', size=24))
  24. plt.plot(x, f, 'r')
  25. plt.plot(x, h, 'r')
  26. def up_data(num):
  27. q = (f - h) / 2 * np.cos(num * x) + (f + h) / 2
  28. plt_love.set_data(x, q)
  29. ani = animation.FuncAnimation(fig=fig, func=up_data, frames=200, interval=100)
  30. ani.save("E:\\love.gif")
  31. os.startfile("E:\\love.gif")

预览
love.gif

数据案例

下载地址: http://data.dream52.cn/python/matplotlib/hw/500.csv

有趣的公式

心形公式
image.png

注意事项

Nothing…

python环境

电脑:Windows10

python:3.10.4