jupyter notebook绘制折线对比图
时间: 2023-09-27 19:05:15 浏览: 163
好的,可以通过matplotlib库在jupyter notebook中绘制折线对比图。首先,需要导入matplotlib库和pandas库。然后加载数据文件并使用plot()函数来进行绘图。如需绘制多个折线图进行对比,可以在同一图表中绘制多个线条并使用legend()函数来设置图例。希望这个回答对你有帮助!
相关问题
jupyter notebook 对比折线图
Jupyter Notebook是一个交互式笔记本,可以用于数据清理和转换,数值模拟,统计建模,数据可视化,机器学习等多个领域。而Matplotlib是Python中最常用的绘图库之一,可以用于绘制各种类型的图表,包括折线图。下面是Jupyter Notebook和Matplotlib绘制折线图的对比:
1. Jupyter Notebook绘制折线图
在Jupyter Notebook中,可以使用Python的matplotlib库来绘制折线图。下面是一个简单的例子:
```python
import matplotlib.pyplot as plt
# x轴数据
x = [1, 2, 3, 4, 5]
# y轴数据
y = [1, 4, 9, 16, 25]
# 绘制折线图
plt.plot(x, y)
# 设置图表标题和坐标轴标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14)
# 显示图表
plt.show()
```
2. Matplotlib绘制折线图
在Matplotlib中,可以使用pyplot模块来绘制折线图。下面是一个简单的例子:
```python
import matplotlib.pyplot as plt
# x轴数据
x = [1, 2, 3, 4, 5]
# y轴数据
y = [1, 4, 9, 16, 25]
# 绘制折线图
plt.plot(x, y)
# 设置图表标题和坐标轴标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14)
# 显示图表
plt.show()
```
可以看到,Jupyter Notebook和Matplotlib绘制折线图的代码非常相似,只是导入库的方式略有不同。在Jupyter Notebook中,需要在代码单元格中导入matplotlib库并使用plt.show()函数来显示图表;而在Matplotlib中,需要使用pyplot模块来绘制图表并使用plt.show()函数来显示图表。
jupyter notebook 网页爬取数据可视化,柱状图,饼状图,散点图,折线图
### 使用 Python 在 Jupyter Notebook 中进行网页爬取并实现数据可视化
#### 准备工作
为了完成此任务,需要安装一些必要的库。可以通过 `pip` 或者 `conda` 来安装所需的包。
```bash
!pip install requests beautifulsoup4 matplotlib seaborn pandas jupyter
```
#### 导入所需模块
在 Jupyter Notebook 开始之前,先导入所有需要用到的 Python 库:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set(style="whitegrid") # 设置 Seaborn 风格
plt.rcParams['font.sans-serif']=['SimHei'] # 解决中文显示问题
plt.rcParams['axes.unicode_minus']=False # 负号正常显示
```
#### 网页爬虫部分
下面是一个简单的例子来说明如何利用 `requests` 和 `BeautifulSoup` 获取 HTML 页面内容,并解析其中的信息。
假设要从某个网站获取书籍销售排名列表作为示例数据集:
```python
url = 'https://example.com/book_sales' # 替换成实际网址
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
titles = []
sales = []
for item in soup.find_all('div', class_='book-item'):
title = item.h2.a.string.strip()
sale = int(item.span.string.replace(',', ''))
titles.append(title)
sales.append(sale)
data = {'Title': titles, 'Sales': sales}
df_booksales = pd.DataFrame(data)
print(df_booksales.head())
```
#### 数据清洗与处理
确保所获得的数据适合用于绘图前可能还需要进一步清理和转换。这里简单地检查是否有缺失值或异常情况即可。
```python
# 查看是否存在空值
missing_values = df_booksales.isnull().sum()
# 如果有重复项则删除它们
duplicate_rows = df_booksales.duplicated().sum()
cleaned_df = df_booksales.drop_duplicates()
print(f"Missing Values:\n{missing_values}\n\nDuplicate Rows Count:{duplicate_rows}")
```
#### 创建不同类型的图表
##### 柱状图 (Bar Chart)
使用 Matplotlib 可以很容易地制作柱状图表示每本书籍对应的销量。
```python
fig, ax = plt.subplots(figsize=(10,7))
ax.bar(cleaned_df['Title'], cleaned_df['Sales'])
ax.set_title('各书本销量对比')
ax.set_xlabel('书名')
ax.set_ylabel('销量数量')
for tick in ax.get_xticklabels():
tick.set_rotation(90) # 让标签垂直排列以便阅读
plt.tight_layout()
plt.show()
```
##### 饼状图 (Pie Chart)
当想要展示各个类别占总体的比例关系时可以选择饼图。
```python
sales_sum = sum(cleaned_df['Sales'])
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return '{p:.2f}% ({v:d})'.format(p=pct,v=val)
return my_autopct
plt.figure(figsize=[8,6])
wedges,texts,autotexts=plt.pie(
cleaned_df['Sales'],
labels=cleaned_df['Title'],
autopct=make_autopct(cleaned_df['Sales']),
startangle=90,
pctdistance=.85,
labeldistance=1.05
);
centre_circle = plt.Circle((0,0),0.70,fc='white') # 添加中心空白圆圈使图形看起来像甜甜圈形状
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.axis('equal')
plt.title("各类别占比", y=1.08)
plt.legend(wedges, cleaned_df['Title'], loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
plt.tight_layout()
plt.show()
```
##### 散点图 (Scatter Plot)
如果希望探索两个变量之间的潜在联系,则可以考虑绘制散点图。
```python
plt.figure(figsize=(10,6))
sns.scatterplot(x='Title', y='Sales', data=cleaned_df)
plt.xticks(rotation=90)
plt.title('书名 vs 销量分布')
plt.xlabel('书名')
plt.ylabel('销量数')
plt.tight_layout()
plt.show()
```
##### 折线图 (Line Chart)
对于时间序列或者其他有序数值的变化趋势来说,折线图是非常有用的工具。
```python
sorted_by_index = cleaned_df.sort_values(by=["Sales"], ascending=False).reset_index(drop=True)
plt.figure(figsize=(10,6))
plt.plot(sorted_by_index.index.values.tolist(), sorted_by_index.Sales.values.tolist())
plt.fill_between(sorted_by_index.index.values.tolist(),
sorted_by_index.Sales.values.tolist(),
color="#ADD8E6")
plt.title('按销量排序后的变化曲线')
plt.xlabel('索引位置')
plt.ylabel('销量数目')
plt.grid(True)
plt.tight_layout()
plt.show()
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)