分析下列代码: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()` 才能显示图像。