jupyter怎么绘制对比柱状图
时间: 2023-10-29 13:23:34 浏览: 298
您可以使用matplotlib库来绘制对比柱状图。首先导入matplotlib库并设置数据,然后使用bar函数绘制两组数据的柱状图,并使用legend函数添加图例,最后使用show函数显示图形。示例代码如下:
```python
import matplotlib.pyplot as plt
# 设置数据
labels = ['A', 'B', 'C', 'D', 'E']
values1 = [10, 20, 30, 40, 50]
values2 = [20, 30, 10, 50, 40]
# 绘制柱状图
plt.bar(labels, values1, alpha=0.7, label='Group 1')
plt.bar(labels, values2, alpha=0.7, label='Group 2')
plt.legend()
# 添加图标题和坐标轴标签
plt.title('Comparison of two groups')
plt.xlabel('Category')
plt.ylabel('Value')
# 显示图形
plt.show()
```
运行上述代码即可得到如下对比柱状图:
![对比柱状图](https://cdn.jsdelivr.net/gh/yzy-chen/assets/images/2022/01/25/jupyter_matplotlib_bar.png)
相关问题
.使用Jupyter notebok工具,使用随机数据绘制’武汉‘和’咸宁‘一天24小时的温度对比的柱状图。
好的,我可以回答这个问题。以下是使用 Jupyter Notebook 工具,使用随机数据绘制武汉和咸宁一天24小时的温度对比的柱状图的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机温度数据
wuhan_temp = np.random.randint(10, 35, size=24)
xianning_temp = np.random.randint(10, 35, size=24)
# 绘制柱状图
plt.bar(range(24), wuhan_temp, label='武汉')
plt.bar(range(24), xianning_temp, label='咸宁')
plt.legend()
plt.xlabel('小时')
plt.ylabel('温度')
plt.title('武汉和咸宁一天24小时的温度对比')
plt.show()
```
希望这个代码可以帮助你绘制出武汉和咸宁一天24小时的温度对比的柱状图。
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()
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](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://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)