Python uses matplotlib to draw graphics

Draw a line chart

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
#防止中文图例, 标题, 横坐标,等出现中文乱码的
mpl.rcParams['font.sans-serif'] = ['FangSong']
x = np.arange(0, 1, 0.05)
y = np.sin(2*np.pi*x)
#lable: 设置图例, 必须要添加:plt.legend('best')
plt.plot(x, y, 'b--*', label='sin')
#图名字
plt.title('my plot')
#横坐标
plt.xlabel('x')
#纵坐标
plt.ylabel('y')
plt.legend('best')
plt.show()

Result display:
Insert picture description here## Draw multiple subgraphs in a picture

x = np.arange(0, 1, 0.05)
y = np.sin(2*np.pi*x)
y2 = np.cos(2*np.pi*x)
fig, ax = plt.subplots(2, 2)
#ax[0,0]: 第一行第一个图片绘制
ax[0, 0].plot(x, y)
ax[0, 1].plot(x, y2 )
plt.show()

Result display:
Insert picture description here

Draw multiple in one picture

x = np.arange(0, 1, 0.05)
y = np.sin(2*np.pi*x)
y2 = np.cos(2*np.pi*x)
fig, ax = plt.subplots()
ax.plot(x, y2)
ax.plot(x, y)
plt.show()

Result display:
Insert picture description here## Read csv file and draw graph

#读取某一列数据: df[列名]
df = pd.read_csv('data.csv', index_col='年份')
x = df.index.values
y = df['啤酒产量(万千升)'].values
#设置间距: explode = [0, 0.05, 0.1 ....]
plt.plot(x, y, 'b--*')
plt.show()

Result display:
Insert picture description here## Draw a pie chart: plt.pie()

设置间距: explode = [0, 0.05, 0.1 ....]
df = pd.read_csv('data.csv', index_col='年份')
x = df.index.values
y = df['啤酒产量(万千升)'].values
#设置间距: explode = [0, 0.05, 0.1 ....]
plt.pie(x, labels=x)
plt.show()

Result display:
Insert picture description here

Draw a bar chart: plt.bar()

df = pd.read_csv('data.csv', index_col='年份')
x = df.index.values
y = df['啤酒产量(万千升)'].values
plt.bar(x, y)
plt.show()

Result display:
Insert picture description here

Draw a scatter chart: scatter

from pylab import mpl
#防止中文图例, 标题, 横坐标,等出现中文乱码的
data = np.random.randint(0, 100, size=[40, 40])
x, y = data[0], data[1]
ax = plt.subplot(111)
ax.scatter(x, y, c='b')
ax.scatter(x[10:20], y[10:20], c='r')
plt.show()

Result display:
Insert picture description here

Draw a three-dimensional scatter plot

data = np.random.randint(0, 100, size=[40, 40])
from mpl_toolkits.mplot3d import Axes3D
x, y, z = data[0], data[1], data[2]
ax = plt.subplot(111, projection='3d')
ax.scatter(x, y, z)
plt.show()

Result display:
Insert picture description here

Draw a word cloud diagram

with open('classify_model1.csv', encoding='utf-8') as f:
    data = f.read()
from wordcloud import WordCloud
word = WordCloud(font_path='C:/Windows/Fonts/simfang.ttf').generate(data)
image = word.to_image()
image.show()

Result display:
Insert picture description here

Guess you like

Origin blog.csdn.net/xxy_yang/article/details/107249748