matlablib经典题⽬1. 绘制⼀个柱状图,写出代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator#从pyplot导⼊MultipleLocator类,这个类⽤于设置刻度间隔#x坐标['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
x_list =[]
for i in range(65,73):
x_list.append(chr(i))
#y坐标
data =[2.5,1,4,4.5,8,8.5,6.5,2]
plt.bar(x_list,data)
matlab生成随机数#设置y轴刻度
y_major_locator=MultipleLocator(2)#把y轴的刻度间隔设置为2,并存在变量⾥
a()#ax为两条坐标轴的实例
ax.yaxis.set_major_locator(y_major_locator)#把y轴的主刻度设置为2的倍数
plt.ylim(0,9)#把y轴的刻度范围设置为0到9
plt.show()
import matplotlib.pyplot as plt
x =[1,2,3,4,5,6,7,8]
y =[3,1,4,5,8,9,7,2]
label=['A','B','C','D','E','F','G','H']
plt.bar(x,y,tick_label = label);
2. 绘制 x=(0,10)间 sin 的图像,设置线性为虚线
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,30)#第单个参数决定图形构成元素数量可以改为80
plt.plot(x, np.sin(x),'--');#第三个参数决定图形元素可以改为+
3. ⽤散点图及颜⾊展⽰⼀组 4 维数据,代码如下,要求:给每⾏代码做注释,详细解释每个函数以及参数的意义
import numpy as np#导⼊numpy库并起别名为np
import matplotlib.pyplot as plt#导⼊pyplot
rng = np.random.RandomState(0)#以0为随机种⼦⽣成伪随机数
x = rng.randn(100)#返回有100的随机项的数组
y = rng.randn(100)#返回有100的随机项的数组
colors = rng.rand(100)#产⽣100个服从“0~1”均匀分布的随机样本值
sizes =1000* rng.rand(100)#产⽣100个服从“0~1”均匀分布的随机样本值
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,#sizes规定⼤⼩,cmap是翡翠⾊
cmap='viridis')# alpha是标量,介于0(透明)与1(不透明)之间
4. ⽤pandas实现下列列表.要求:
①编写代码实现下图内容
②并且显⽰前5⾏内容
③显⽰最后3⾏内容
④把下图按照age升序排序
import numpy as np
import pandas as pd
row_index =[]#⾏索引为['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
for i in range(97,107):
row_index.append(chr(i))
data_cols ={
"animal":["cat","cat","snake","dog","dog","cat","snake","cat","dog","dog"], "age":["2.5","3.0","0.5","NaN","5.0","2.0","4.5","NaN","7.0","3.0"],
"priority":["yes","yes","no","yes","no","no","no","yes","no","no"],
"visits":["1","3","2","3","2","3","1","1","2","1"]
}
#输出DF表格
df = pd.DataFrame(data_cols,index=row_index)
print(df)
print("\n")
#显⽰前5⾏
print(df.head(5))
print("\n")
#显⽰后3⾏
print(df.tail(3))
print("\n")
#按照age升序排列
df.sort_values(['age'])
print(df)
animal age priority visits
a cat 2.5 yes 1
b cat 3.0 yes 3
c snake 0.5 no 2
d dog NaN yes 3
e dog 5.0 no 2
f cat 2.0 no 3
g snake 4.5 no 1
h cat NaN yes 1
i dog 7.0 no 2 j dog 3.0 no 1
animal age priority visits
a cat 2.5 yes 1
b cat 3.0 yes 3
c snake 0.5 no 2
d dog NaN yes 3
e dog 5.0 no 2
animal age priority visits
h cat NaN yes 1
i dog 7.0 no 2 j dog 3.0 no 1
animal age priority visits
a cat 2.5 yes 1
b cat 3.0 yes 3
c snake 0.5 no 2
d dog NaN yes 3
e dog 5.0 no 2
f cat 2.0 no 3
g snake 4.5 no 1
h cat NaN yes 1
i dog 7.0 no 2 j dog 3.0 no 1
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论