分析下列代码:import pandas as pd import matplotlib.pyplot as plt data = pd.read_excel("E:\\爬取\\爬取.xls") year_count = data.groupby(by="年份")["年份"].count() data['年份'] = pd.to_numeric(data['年份'], errors='coerce') plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams['axes.unicode_minus'] = False plt.plot(year_count.index, year_count.values) plt.title("电影年份发展折线图") plt.xlabel("年份") plt.ylabel("数量") plt.show() import pandas as pd import matplotlib.pyplot as plt data = pd.read_excel("E:\\爬取\\爬取.xls") plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams['axes.unicode_minus'] = False year_count = data['国家'].value_counts() plt.bar(year_count.index, year_count.values) plt.title("各个国家电影数量") plt.xlabel("国家") plt.ylabel("电影数量") plt.show() import pandas as pd import matplotlib.pyplot as plt data = pd.read_excel("E:\\爬取\\爬取.xls") plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams['axes.unicode_minus'] = False type_count = data["类型"].value_counts() plt.pie(type_count,labels=type_count.index,pctdistance=0.8,autopct='%1.1f%%',explode=[0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.01]) plt.figure(figsize=(20,6.5)) plt.title("电影主要类型分布图") plt.show() import pandas as pd import matplotlib.pyplot as plt data = pd.read_excel("E:\\爬取\\爬取.xls") scores = data["排名"].values votes = data["评价人数"].values plt.rcParams["font.sans-serif"] = ["SimHei"] plt.scatter(scores, votes) plt.title("排名与评价人数散点图") plt.xlabel("排名") plt.ylabel("评价人数") plt.show()

时间: 2024-04-28 07:27:09 浏览: 12
这段代码主要是用来对爬取到的电影数据进行数据可视化的处理。在代码中使用了 pandas 库对 Excel 数据进行读取和处理,使用了 matplotlib 库来绘制各种图表。 第一个代码块绘制了电影年份的发展折线图,其中先对年份进行了分组统计,然后使用 plot 函数将结果绘制出来。 第二个代码块绘制了各个国家电影数量的柱状图,其中使用了 value_counts 函数对国家进行统计,然后使用 bar 函数将结果绘制出来。 第三个代码块绘制了电影主要类型分布的饼图,其中使用了 value_counts 函数对电影类型进行统计,然后使用 pie 函数将结果绘制出来。 第四个代码块绘制了排名与评价人数的散点图,其中使用了 scatter 函数将排名和评价人数进行散点绘制。
相关问题

import tkinter as tk import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import os class ExcelPlotter(tk.Frame): def init(self, master=None): super().init(master) self.master = master self.master.title("图方便") self.file_label = tk.Label(master=self, text="Excel File Path:") self.file_label.grid(row=0, column=0, sticky="w") self.file_entry = tk.Entry(master=self) self.file_entry.grid(row=0, column=1, columnspan=2, sticky="we") self.file_button = tk.Button(master=self, text="Open", command=self.open_file) self.file_button.grid(row=0, column=3, sticky="e") self.plot_button = tk.Button(master=self, text="Plot", command=self.plot_data) self.plot_button.grid(row=1, column=2, sticky="we") self.name_label = tk.Label(master=self, text="Out Image Name:") self.name_label.grid(row=2, column=0, sticky="w") self.name_entry = tk.Entry(master=self) self.name_entry.grid(row=2, column=1, columnspan=2, sticky="we") self.save_button = tk.Button(master=self, text="Save", command=self.save_image) self.save_button.grid(row=2, column=3, sticky="e") self.figure = plt.figure(figsize=(5, 4), dpi=150) self.canvas = FigureCanvasTkAgg(self.figure, master=self) self.canvas.get_tk_widget().grid(row=4, column=0, columnspan=4, sticky="we") self.pack() def open_file(self): file_path = tk.filedialog.askopenfilename(filetypes=[("Excel Files", "*.xls")]) self.file_entry.delete(0, tk.END) self.file_entry.insert(tk.END, file_path) def plot_data(self): file_path = self.file_entry.get() if os.path.exists(file_path): data = pd.read_excel(file_path) plt.plot(data['波长(nm)'], data['吸光度'], 'k') plt.xlim(300, 1000) plt.xlabel('Wavelength(nm)', fontsize=16) plt.ylabel('Abs.', fontsize=16) plt.gcf().subplots_adjust(left=0.13, top=0.91, bottom=0.16) plt.savefig('Last Fig', dpi=1000) plt.show() def save_image(self): if self.figure: file_path = tk.filedialog.asksaveasfilename(defaultextension=".png") if file_path: self.figure.savefig(file_path) root = tk.Tk() app = ExcelPlotter(master=root) app.mainloop()帮我增加一个删除当前图像的功能

好的,您可以在 `ExcelPlotter` 类中添加一个名为 `delete_image` 的方法,实现删除当前图像的功能。可以在该方法中调用 `self.figure.clf()` 清空当前图像,然后在界面上更新显示。下面是修改后的代码: ```python import tkinter as tk import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import os class ExcelPlotter(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.title("图方便") self.file_label = tk.Label(master=self, text="Excel File Path:") self.file_label.grid(row=0, column=0, sticky="w") self.file_entry = tk.Entry(master=self) self.file_entry.grid(row=0, column=1, columnspan=2, sticky="we") self.file_button = tk.Button(master=self, text="Open", command=self.open_file) self.file_button.grid(row=0, column=3, sticky="e") self.plot_button = tk.Button(master=self, text="Plot", command=self.plot_data) self.plot_button.grid(row=1, column=2, sticky="we") self.delete_button = tk.Button(master=self, text="Delete", command=self.delete_image) self.delete_button.grid(row=1, column=3, sticky="e") self.name_label = tk.Label(master=self, text="Out Image Name:") self.name_label.grid(row=2, column=0, sticky="w") self.name_entry = tk.Entry(master=self) self.name_entry.grid(row=2, column=1, columnspan=2, sticky="we") self.save_button = tk.Button(master=self, text="Save", command=self.save_image) self.save_button.grid(row=2, column=3, sticky="e") self.figure = plt.figure(figsize=(5, 4), dpi=150) self.canvas = FigureCanvasTkAgg(self.figure, master=self) self.canvas.get_tk_widget().grid(row=4, column=0, columnspan=4, sticky="we") self.pack() def open_file(self): file_path = tk.filedialog.askopenfilename(filetypes=[("Excel Files", "*.xls")]) self.file_entry.delete(0, tk.END) self.file_entry.insert(tk.END, file_path) def plot_data(self): file_path = self.file_entry.get() if os.path.exists(file_path): data = pd.read_excel(file_path) plt.plot(data['波长(nm)'], data['吸光度'], 'k') plt.xlim(300, 1000) plt.xlabel('Wavelength(nm)', fontsize=16) plt.ylabel('Abs.', fontsize=16) plt.gcf().subplots_adjust(left=0.13, top=0.91, bottom=0.16) plt.show() def delete_image(self): if self.figure: self.figure.clf() self.canvas.draw() def save_image(self): if self.figure: file_path = tk.filedialog.asksaveasfilename(defaultextension=".png") if file_path: self.figure.savefig(file_path) root = tk.Tk() app = ExcelPlotter(master=root) app.mainloop() ``` 在界面上添加了一个名为 `Delete` 的按钮,点击该按钮会调用 `delete_image` 方法。该方法会清空当前图像并在界面上更新显示。

这串代码结果显示Bar不是有效的plot kind,要如何改进。import pandas as pd data = pd.read_excel('titanic.xls') print(data.sex.unique()) data.loc[data['sex']=='male','sex']=0 data.loc[data['sex']=='female','sex']=1 survive_0 = data['survived'][data['sex']==0].value_counts() survive_1 = data['survived'][data['sex']==1].value_counts() data1 =pd.DataFrame({'获救': survive_1,'未获救': survive_0}) data1.plot(kind='Bar',stacked=True) plt.title('不同性别的获救比例')

把 `Bar` 改为 `bar` 即可,这个错误是因为大小写不匹配导致的。修改后的代码如下: ``` import pandas as pd import matplotlib.pyplot as plt data = pd.read_excel('titanic.xls') print(data.sex.unique()) data.loc[data['sex']=='male','sex']=0 data.loc[data['sex']=='female','sex']=1 survive_0 = data['survived'][data['sex']==0].value_counts() survive_1 = data['survived'][data['sex']==1].value_counts() data1 = pd.DataFrame({'获救': survive_1,'未获救': survive_0}) data1.plot(kind='bar', stacked=True) plt.title('不同性别的获救比例') plt.show() ``` 注意最后需要加上 `plt.show()` 才能显示图像。

相关推荐

请在在以下代码中添加可以标准化新字段“R”、“F”、“M”数据的代码:import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime plt.rcParams["font.sans-serif"]=["Microsoft YaHei"] #设置字体 plt.rcParams["axes.unicode_minus"]=False #解决"-"负号乱码问题 import warnings warnings.filterwarnings('ignore') import pandas as pd # 读取Excel文件,并将“订单”工作表读取为数据框 df = pd.read_excel('/home/mw/input/superstore8223/商城详细销售数据.xls', sheet_name='订单') # 输出数据框的基本信息 print("数据框的行数:", df.shape[0]) # 行数 print("数据框的列数:", df.shape[1]) # 列数 print("数据框的字段名称:", df.columns.tolist()) # 字段名称 print("数据框的字段类型:", df.dtypes.tolist()) # 字段类型 print("数据框的前5行:\n", df.head()) # 前5行数据 df = pd.read_excel('/home/mw/input/superstore8223/商城详细销售数据.xls') df_rfm = df.groupby('客户 ID').agg({'销售额':sum,'订单日期':[pd.Series.nunique,'max']}) ##计算 F、M df_rfm.columns = df_rfm.columns.droplevel() df_rfm.columns = ['Amount','Frequency','Time'] df_rfm['Amount'] = df_rfm['Amount'].map(lambda x:round(x,2)) statistics_date = datetime.strptime('2019-01-06',"%Y-%m-%d") df_rfm['Last_purchase'] = df_rfm['Time'].map(lambda x:(statistics_date - x).days) ##计算 R data = df_rfm[['Last_purchase','Frequency','Amount']] data.columns = ['R','F','M'] data.to_excel('RFM_data.xlsx')

''' # 钱包余额 money= 50 # 消费后 ice = 10 colo = 5 money= money-ice-colo print('钱包余额:',money,'元') name = '传智播客' stock_price = 19.99 stock_code = "003032" stock_price_daily_grown_factor = 1.2 grown_days = 7 finally_stock_price=stock_price * stock_price_daily_grown_factor ** grown_days print(f"公司:{name},股票代码:{stock_code},当前股价{stock_price}") print("每日的增长系数是:%.1f,经过%d的增长后,股价达到了:%.2f"%(stock_price_daily_grown_factor,grown_days,finally_stock import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import xlwt df = pd.read_excel(r"D:\学习\Employee_income.xls",sheet_name='emp_income') # 选择数值列进行计算 df_numeric = df.select_dtypes(include=np.number) corrresult1=df_numeric['age'].corr(df_numeric['salary']) print('age和salary的相关系数',corrresult1) corrresult2=df_numeric.loc[:,['age', 'salary', 'subsidy']].corr() print('age和salary、subsidy的相关系数\n',corrresult2) print('返回个相关系数矩阵\n',df_numeric.corr()) corrresult3=df_numeric.corr() print('返回一个相关系数矩阵\n', corrresult3) sns.heatmap(corrresult3, annot=True, cmap='YlGnBu', linewidths=1.2) plt.show() ''' import pandas as pd import numpy as np data = pd.read_csv(r"D:\学习\goods_sales.csv",encoding='GBK') print(data) newData = data['商品信息'].str.split(';',3,True) newData.columns = ['品牌','分类','型号'] print(newData) df = data.drop('商品信息',axis=1).join(newData) result = df.groupby(by=['品牌'])['数量'].agg({'数量':np.sum}) print(result) telData = data['电话'].astype(str) areas = telData.str.slice(3,7) print(areas) newDf = data.drop('电话',axis=1).join(areas) print(newDf) result = newDf.groupby(by=['电话'])['数量'].agg({'数量':np.sum}) print(result)

import numpy as np import pandas as pd import matplotlib.pyplot as plt import BPNN from sklearn import metrics from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error #导入必要的库 df1=pd.read_excel(r'D:\Users\Desktop\大数据\44.xls',0) df1=df1.iloc[:,:] #进行数据归一化 from sklearn import preprocessing min_max_scaler = preprocessing.MinMaxScaler() df0=min_max_scaler.fit_transform(df1) df = pd.DataFrame(df0, columns=df1.columns) x=df.iloc[:,:4] y=df.iloc[:,-1] #划分训练集测试集 cut=4#取最后cut=30天为测试集 x_train, x_test=x.iloc[4:],x.iloc[:4]#列表的切片操作,X.iloc[0:2400,0:7]即为1-2400行,1-7列 y_train, y_test=y.iloc[4:],y.iloc[:4] x_train, x_test=x_train.values, x_test.values y_train, y_test=y_train.values, y_test.values #神经网络搭建 bp1 = BPNN.BPNNRegression([4, 16, 1]) train_data=[[sx.reshape(4,1),sy.reshape(1,1)] for sx,sy in zip(x_train,y_train)] test_data = [np.reshape(sx,(4,1))for sx in x_test] #神经网络训练 bp1.MSGD(train_data, 1000, len(train_data), 0.2) #神经网络预测 y_predict=bp1.predict(test_data) y_pre = np.array(y_predict) # 列表转数组 y_pre=y_pre.reshape(4,1) y_pre=y_pre[:,0] #画图 #展示在测试集上的表现 draw=pd.concat([pd.DataFrame(y_test),pd.DataFrame(y_pre)],axis=1); draw.iloc[:,0].plot(figsize=(12,6)) draw.iloc[:,1].plot(figsize=(12,6)) plt.legend(('real', 'predict'),loc='upper right',fontsize='15') plt.title("Test Data",fontsize='30') #添加标题 #输出精度指标 print('测试集上的MAE/MSE') print(mean_absolute_error(y_pre, y_test)) print(mean_squared_error(y_pre, y_test) ) mape = np.mean(np.abs((y_pre-y_test)/(y_test)))*100 print('=============mape==============') print(mape,'%') # 画出真实数据和预测数据的对比曲线图 print("R2 = ",metrics.r2_score(y_test, y_pre)) # R2 运行上述程序。在下面这一步中draw=pd.concat([pd.DataFrame(y_test),pd.DataFrame(y_pre)],axis=1);我需要将归一化的数据变成真实值,输出对比图,该怎么修改程序

最新推荐

recommend-type

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

导入numpy库,创建两个包含9个随机数的3*3的矩阵,将两个矩阵分别打印出来,计算两个数组的点积并打印出来。(random.randn()、dot()函数)

可以的,以下是代码实现: ```python import numpy as np # 创建两个包含9个随机数的3*3的矩阵 matrix1 = np.random.randn(3, 3) matrix2 = np.random.randn(3, 3) # 打印两个矩阵 print("Matrix 1:\n", matrix1) print("Matrix 2:\n", matrix2) # 计算两个数组的点积并打印出来 dot_product = np.dot(matrix1, matrix2) print("Dot product:\n", dot_product) ``` 希望
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。