python3 matplotlib 2D图各种函数图

本文详细介绍了如何使用Python3的matplotlib库绘制2D图表,包括折线图、一元二次函数、三角函数、散点图、圆饼图、柱状图、正态分布和等高线图的绘制方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

折线图

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
squares=[1,4,9,16,25]

plt.plot(x,squares,linewidth=5) #设置线条宽度
#设置中文乱码问题
plt.rcParams['font.sans-serif'] = ['SimHei']
#设置图标标题,并在坐标轴上添加标签
plt.title('标题设置',fontsize=24)
plt.xlabel('x轴',fontsize=14)
plt.ylabel('y轴',fontsize=14)

plt.show()

运行截图

import matplotlib.pyplot as plt
#200个点的x坐标
x=range(-100,100)
#生成y点的坐标
y=[i**2 for i in x ]
#绘制一元二次曲线
plt.plot(x,y)
#调用savefig将一元二次曲线保存为result.jpg
plt.savefig('result.jpg') #如果直接写成 plt.savefig('cos') 会生成cos.png
plt.show()

一元二次函数

运行结果

三角函数

import matplotlib.pyplot as plt
import numpy as np
#生成x的坐标(0-10的100个等差数列)
x=np.linspace(0,10,100)
sin_y=np.sin(x)
#绘制正弦曲线
plt.plot(x,sin_y)
#绘制余弦曲线
cos_y=np.cos(x)
plt.plot(x,cos_y)
plt.show()

运行结果

散点图

import matplotlib.pyplot as plt
import numpy as np
#画10种大小, 100种颜色的散点图
np.random.seed(0)
x=np.random.rand(100)
y=np.random.rand(100)
colors=np.random.rand(100)
size=np.random.rand(10)*1000
plt.scatter(x,y,c=colors,s=size,alpha=0.7)
plt.show()

运行结果

圆饼图

import matplotlib.pyplot as plt
import numpy as np
#准备男、女的人数及比例
man=71351
woman=68187
man_perc=man/(woman+man)
woman_perc=woman/(woman+man)
#添加名称
labels=['男','女']
#添加颜色
colors=['blue','red']
#绘制饼状图  pie
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
#labels 名称 colors:颜色,explode=分裂  autopct显示百分比
paches,texts,autotexts=plt.pie([man_perc,woman_perc],labels=labels,colors=colors,explode=(0,0.05),autopct='%0.1f%%')

#设置饼状图中的字体颜色
for text in autotexts:
    text.set_color('white')

#设置字体大小
for text in texts+autotexts:
    text.set_fontsize(20)
plt.show()

运行结果

柱状图

import matplotlib.pyplot as plt
import numpy as np
#三天中三部电影的票房变化
real_names=['千与千寻','玩具总动员4','黑衣人:全球追缉']
real_num1=[5453,7548,6543]
real_num2=[1840,4013,3421]
real_num3=[1080,1673,2342]
#生成x  第1天   第2天   第3天
x=np.arange(len(real_names))
x_label=['第{}天'.format(i+1) for i in range(len(real_names))]
#绘制柱状图
#设置柱的宽度
width=0.3
plt.bar(x,real_num1,color='g',width=width,label=real_names[0])
plt.bar([i+width for i in x],real_num2,color='b',width=width,label=real_names[1])
plt.bar([i+2*width for i in x],real_num3,color='r',width=width,label=real_names[2])
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
#修改x坐标
plt.xticks([i+width for i in x],x_label)
#添加图例
plt.legend()
#添加标题
plt.title('3天的票房数')
plt.show()

运行结果

正态分布

import numpy as np
import matplotlib.pyplot as plt
#几个直方图画到一个画布中,第一个参数期望  第二个均值
x1=np.random.normal(0,0.8,1000)
x2=np.random.normal(-2,1,1000)
x3=np.random.normal(3,2,1000)
#参数分别是bins:装箱,alpha:透明度
kwargs=dict(bins=100,alpha=0.4)
plt.hist(x1,**kwargs)
plt.hist(x2,**kwargs)
plt.hist(x3,**kwargs)
plt.show()

运行结果

等高线

#导入模块
import matplotlib.pyplot as plt
import numpy as npaa
x=np.linspace(-10,10,100)
y=np.linspace(-10,10,100)
#计算x和y的相交点a
X,Y=np.meshgrid(x,y)
#计算Z的坐标
Z=np.sqrt(X**2+Y**2)
plt.contourf(X,Y,Z)
plt.contour(X,Y,Z)
 颜色越深表示值越小,中间的黑色表示z=0.

plt.show()

运行结果

import itertools
from collections import OrderedDict
from functools import partial

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from cycler import cycler


def filled_hist(ax, edges, values, bottoms=None, orientation='v',
                **kwargs):
    print(orientation)
    if orientation not in 'hv':
        raise ValueError("orientation must be in {{'h', 'v'}} "
                         "not {o}".format(o=orientation))

kwargs.setdefault('step', 'post')
edges = np.asarray(edges)
values = np.asarray(values)
if len(edges) - 1 != len(values):
    raise ValueError('Must provide one more bin edge than value not: '
                     'len(edges): {lb} len(values): {lv}'.format(
                         lb=len(edges), lv=len(values)))

if bottoms is None:
    bottoms = 0
bottoms = np.broadcast_to(bottoms, values.shape)

values = np.r_[values, values[-1]]
bottoms = np.r_[bottoms, bottoms[-1]]
if orientation == 'h':
    return ax.fill_betweenx(edges, values, bottoms,
                            **kwargs)
elif orientation == 'v':
    return ax.fill_between(edges, values, bottoms,
                           **kwargs)
else:
    raise AssertionError("you should never be here")


def stack_hist(ax, stacked_data, sty_cycle, bottoms=None,
               hist_func=None, labels=None,
               plot_func=None, plot_kwargs=None):

# deal with default binning function
if hist_func is None:
    hist_func = np.histogram

# deal with default plotting function
if plot_func is None:
    plot_func = filled_hist

# deal with default
if plot_kwargs is None:
    plot_kwargs = {}
print(plot_kwargs)
try:
    l_keys = stacked_data.keys()
    label_data = True
    if labels is None:
        labels = l_keys

except AttributeError:
    label_data = False
    if labels is None:
        labels = itertools.repeat(None)

if label_data:
    loop_iter = enumerate((stacked_data[lab], lab, s)
                          for lab, s in zip(labels, sty_cycle))
else:
    loop_iter = enumerate(zip(stacked_data, labels, sty_cycle))

arts = {}
for j, (data, label, sty) in loop_iter:
    if label is None:
        label = 'dflt set {n}'.format(n=j)
    label = sty.pop('label', label)
    vals, edges = hist_func(data)
    if bottoms is None:
        bottoms = np.zeros_like(vals)
    top = bottoms + vals
    print(sty)
    sty.update(plot_kwargs)
    print(sty)
    ret = plot_func(ax, edges, top, bottoms=bottoms,
                    label=label, **sty)
    bottoms = top
    arts[label] = ret
ax.legend(fontsize=10)
return arts


#set up histogram function to fixed bins
edges = np.linspace(-3, 3, 20, endpoint=True)
hist_func = partial(np.histogram, bins=edges)

#set up style cycles
color_cycle = cycler(facecolor=plt.rcParams['axes.prop_cycle'][:4])
label_cycle = cycler(label=['set {n}'.format(n=n) for n in range(4)])
hatch_cycle = cycler(hatch=['/', '*', '+', '|'])

#Fixing random state for reproducibility
np.random.seed(19680801)

stack_data = np.random.randn(4, 12250)
dict_data = OrderedDict(zip((c['label'] for c in label_cycle), stack_data))

###############################################################################
#Work with plain arrays

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5), tight_layout=True)
arts = stack_hist(ax1, stack_data, color_cycle + label_cycle + hatch_cycle,
                  hist_func=hist_func)

arts = stack_hist(ax2, stack_data, color_cycle,
                  hist_func=hist_func,
                  plot_kwargs=dict(edgecolor='w', orientation='h'))
ax1.set_ylabel('counts')
ax1.set_xlabel('x')
ax2.set_xlabel('counts')
ax2.set_ylabel('x')

###############################################################################
#Work with labeled data

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5),
                               tight_layout=True, sharey=True)

arts = stack_hist(ax1, dict_data, color_cycle + hatch_cycle,
                  hist_func=hist_func)

arts = stack_hist(ax2, dict_data, color_cycle + hatch_cycle,
                  hist_func=hist_func, labels=['set 0', 'set 3'])
ax1.xaxis.set_major_locator(mticker.MaxNLocator(5))
ax1.set_xlabel('counts')
ax1.set_ylabel('x')
ax2.set_ylabel('x')

plt.show()

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值