目录
文章目录
1、可视化:标题中文显示和防动态显示不完整
'''
可视化中文显示
plt.rcParams["font.family"] = 'Arial Unicode MS' #可视化中文显示
plt.rcParams["animation.embed_limit"]=2**128 #防止动态图显示不完整
'''
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["font.family"] = 'Arial Unicode MS' #可视化中文显示
x=np.arange(1,10,2)
y=x+1
plt.plot(x,y)
plt.title('中文标题中文展示')
plt.show()
2、可视化:读取文件
import pandas as pd
#pycharm里面文件
df =pd.read_excel('.xlsx')
print(df.head(2))
#日常文件
df = pd.read_excel('.xlsx')
3、可视化:背景替换
fig, ax = plt.subplots(figsize=(12,12),dpi=100,facecolor='#1D1E23',edgecolor='#1D1E23')
bgimg = img.imread('kebi.jpeg')
fig.figimage(bgimg, resize=True,alpha=0.3) # ,resize=True
4、python基础语法:时间转换
import time,datetime
'''
字符串类型转换时间
1、转换为时间数组
2、从时间数组里面获取年月日等数字
3、时间数组转为时间戳
'''
tss1 = '2022-01-20 23:40:10'
# 转为时间数组
timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")
print("时间数组:",timeArray)
print("时间数组里面获取年月日等数字:",timeArray.tm_year)
timeStamp = int(time.mktime(timeArray))
print("时间数组转为时间戳:",timeStamp)
'''
日期格式更改
1、2013-10-10 23:40:00修改成:2013/10/10 23:40:00
2、2013/10/10 23:40:00修改成:2013-10-10 23:40:00
'''
tss2 = "2013-10-10 23:40:00"
timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S")
print(timeArray)
otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print(otherStyleTime)
tss3 = "2013/10/10 23:40:00"
timeArray = time.strptime(tss3, "%Y/%m/%d %H:%M:%S")
print(timeArray)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)
'''
时间戳转换为指定格式的日期
1、1381419600 转换成:2013--10--10 23:40:00
2、1381419600 转换成:2013--10--10 23:40:00
3、1381419600 转换成:2013--10--10 15:40:00
'''
# 使用time
timeStamp = 1381419600
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime) # 2013--10--10 23:40:00
# 使用datetime
timeStamp = 1381419600
dateArray = datetime.datetime.fromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
print(otherStyleTime) # 2013--10--10 23:40:00
# 使用datetime,指定utc时间,相差8小时
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
print(otherStyleTime) # 2013--10--10 15:40:00
'''
获取当前时间并且用指定格式显示
1、time获取当前时间戳
2、datetime获取当前时间,数组格式
'''
# time获取当前时间戳
now = int(time.time()) # 1533952277
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)
# datetime获取当前时间,数组格式
now = datetime.datetime.now()
print(now)
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)
5、python基础语法:数据类型查询
#数据类型
type(202101) #输出:<class 'int'>
type('202101') #输出:<class 'str'>
6、pandas语法:pandas基础语法
'''
1、pandas列转换list
2、显示所有列
3、显示所有行
4、设置value的显示长度为100,默认为50
'''
#pandas列转换list
df['时间'].tolist() #输出:[1,2,3]
#显示所有列
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#设置value的显示长度为100,默认为50
pd.set_option('max_colwidth',100)
7、可视化:画布布局
import matplotlib.pyplot as plt
import numpy as np
'''
画布图布局
1、逐个图增加
2、多行多列图
'''
#1、逐个图增加
x = np.arange(1, 100)
plt.subplot(221)
plt.plot(x, x * x)
plt.subplot(223)
plt.pie(x=[15, 30, 45, 10], labels=list('ABCD'), autopct='%.0f', explode=[0, 0.05, 0, 0])
#2、多行多列图
fig,subs=plt.subplots(2,3)
x = np.arange(1, 10, 2)
y = x + 1
subs[0][1].plot(x, y)
subs[1][2].plot(x, y)
plt.show()
8、可视化:坐标系格式调整
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
'''
画布坐标系格式调整
1、标题:title
2、坐标轴范围:axis
3、网格线:grid
4、图例:legend
5、XY轴标题:xlabel、ylabel
6、自定义左边范围:plt.xlim([0, 10])
7、自定义坐标轴刻度:xticks、yticks
8、文本和注释箭头:text、annotate
'''
plt.rcParams["font.family"] = 'Arial Unicode MS'
x = np.arange(1, 6, 2)
y = x + 1
z = x + 2
df = pd.read_excel('.xlsx')
print(df.head(2))
plt.plot(x, y)
plt.plot(x, z)
plt.title('标题',fontsize='15',fontweight='bold',color='blue',loc ='left',verticalalignment='bottom',rotation=0,
bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65))
# plt.axis([1, 5, 1, 11])
plt.grid(color = 'gray', linestyle = '--', linewidth = 1)
plt.legend(labels=['Function 1', 'Function3'], loc='upper right')
# plt.xlim([0, 10])
# plt.ylim([5, 10])
plt.xlabel("x 轴", loc="right") # 横坐标标题
plt.ylabel("y 轴", loc="top") # 纵坐标标题
plt.xticks([0, 25, 50, 75])
# plt.yticks([0, 25, 50, 75])
plt.text(2, 3, "test", size=10, rotation=30., ha="center", va="center",
bbox=dict(boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8), ))
plt.annotate('local max', xy=(2, 3), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
'''
#边框删除
1、上边框删除
2、右边框删除
3、左边框颜色设置
4、底边框颜色设置
5、XY坐标刻度格式:刻度显示,刻度数字大小,颜色,刻度位置在里面还是外面
6、设置刻度范围:ax.axis
7、设置XY轴范围:ax.set_xlim、ax.set_ylim
8、设置刻度数字:ax.set_xticks
9、设置刻度标签显示:ax.set_xticklabels
10、设置网格线: ax.grid
11、设置坐标轴标签:ax.set_xlabel()
12、y轴刻度千分位格式
13、X轴刻度太密集,调整可显示刻度数据
14、插入图片
15、自动调整子图参数
'''
fig, ax = plt.subplots()
x = np.arange(1, 5, 1)
y = x + 1
plt.plot(x,y)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#425663')
ax.spines['bottom'].set_visible('#373E4B')
ax.tick_params(axis='y',bottom=True,labelsize=10,direction='inout',colors='gray')
ax.axis([0, 5, 1, 11])
ax.set_xlim(left=0, right=10)
ax.set_ylim(ymin=0,ymax=15)
ax.set_xticks([0, 250, 500, 750])
ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], rotation=45, fontsize='small')
ax.grid(axis='both',color='gray',lw=1,alpha=.6,ls='--')
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
ax.set_xticks([x[i] for i in range(len(x)) if i % 15 == 0])
arr_img = plt.imread("car.jpeg")
im = OffsetImage(arr_img, zoom=.05)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction', box_alignment=(1.1, -0.1))#(1,0)是插入图片的位置
ax.add_artist(ab)
plt.tight_layout()
plt.show()
9、可视化:动态图展示
'''
动态图展示
1、动态展示
2、保存gif、MP4
'''
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel('.xlsx')
df['时间'] = df['时间'].apply(lambda x: int(x.strftime('%Y%m')))
frames = df['时间'].tolist()
fig, ax = plt.subplots()
def line_animation(current_year):
data = df.loc[df['时间'] <= current_year, :]
idx = data['时间']
# print(data)
a = idx.tolist()
a2 = [str(i) for i in a]
ax.clear()
ax.plot(a2, data['五菱'], color='#FF5872', lw=3)
# line_animation(frames)
line_animation = animation.FuncAnimation(fig, line_animation, frames=frames, interval=350)
# ani.save('sin_x.gif') #保存gif图片
# line_animation.to_html5_video() #将动画效果在jupyter notebook中显示
line_animation.save('car_data.mp4') #保存map4
plt.show()
10、可视化:matplotlib表格
#matplotlib表格
import matplotlib.pyplot as plt
import numpy as np
#列名
col=[]
for i in range(1,8):
col.append("Day"+str(i))
print(col)
#行名
row=[]
for i in range(1,13):
row.append(i)
print(row)
#表格里面的具体值
vals=np.random.rand(12,7)
print(vals)
plt.figure(figsize=(20,8))
tab = plt.table(cellText=vals,
colLabels=col,
rowLabels=row,
loc='center',
cellLoc='center',
rowLoc='center')
tab.auto_set_font_size(False)#关闭字体自适应
tab.set_fontsize(10)#设置字体大小
tab.scale(1,2)
plt.axis('off')
plt.show()