Python数据可视化与单变量分析指南
立即解锁
发布时间: 2025-09-03 00:37:26 阅读量: 12 订阅数: 20 AIGC 


Python探索性数据分析实战
### Python 数据可视化与单变量分析指南
在数据分析中,可视化数据和进行单变量分析是非常重要的环节。本文将介绍如何使用 Python 中的不同库进行数据可视化和单变量分析,包括使用 Bokeh 库绘制条形图和子图,以及使用 seaborn 库进行直方图、箱线图、小提琴图和摘要表的绘制。
#### 1. 使用 Bokeh 进行数据可视化
Bokeh 是一个强大的 Python 库,可用于创建交互式可视化图表。以下是使用 Bokeh 绘制条形图和子图的步骤:
1. **导入必要的库**:
```python
import pandas as pd
from bokeh.plotting import figure, show, output_notebook
import bokeh.plotting as bk_plot
```
2. **加载数据**:
```python
houseprices_data = pd.read_csv("your_file.csv")
```
3. **数据检查**:
```python
print(houseprices_data.head())
print(houseprices_data.dtypes)
print(houseprices_data.shape)
```
4. **创建每平方米价格变量**:(假设你有相关列)
```python
houseprices_data['price_per_sq_meter'] = houseprices_data['Price'] / houseprices_data['Area']
```
5. **按价格排序**:
```python
houseprices_data = houseprices_data.sort_values(by='Price')
```
6. **绘制条形图**:
```python
output_notebook()
p = figure(x_range=houseprices_data['Zip'], width=800, height=400)
p.vbar(x=houseprices_data['Zip'], top=houseprices_data['Price'], width=0.9)
```
7. **添加图表细节**:
```python
p.title.text = "Top 10 Areas by House Price"
p.xaxis.axis_label = "Zip Code"
p.yaxis.axis_label = "House Price"
p.title.text_font_size = "16pt"
p.xaxis.axis_label_text_font_size = "12pt"
p.yaxis.axis_label_text_font_size = "12pt"
p.xaxis.major_label_text_font_size = "10pt"
p.yaxis.major_label_text_font_size = "10pt"
show(p)
```
8. **创建子图**:
```python
from bokeh.layouts import gridplot
p1 = figure(width=400, height=400)
p1.circle(houseprices_data['Area'], houseprices_data['Price'])
p2 = figure(width=400, height=400)
p2.line(houseprices_data['Room'], houseprices_data['Price'])
grid = gridplot([[p1, p2]])
show(grid)
```
Bokeh 提供了许多交互式功能,如缩放、平移和悬停。除了基本的交互功能外,还可以通过回调和小部件实现更复杂的交互。
#### 2. 使用 seaborn 进行单变量分析
seaborn 是一个基于 matplotlib 的 Python 数据可视化库,可用于创建各种统计图表。以下是使用 seaborn 进行单变量分析的几种方法:
##### 2.1 直方图
直方图是一种用于展示连续变量频率分布的图表。以下是创建直方图的步骤:
1. **导入必要的库**:
```python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
```
2. **加载数据**:
```python
penguins_data = pd.read_csv("data/penguins_size.csv")
penguins_data = penguins_data[['species', 'culmen_length_mm']]
```
3. **数据检查**:
```python
print(penguins_data.head())
print(penguins_data.shape)
print(penguins_data.dtypes)
```
4. **创建直方图**:
```python
sns.histplot(data=penguins_data, x=penguins_data["culmen_length_mm"])
```
5. **添加图表细节**:
```python
plt.figure(figsize=(12, 6))
ax = sns.histplot(data=penguins_data, x=penguins_data["cul
```
0
0
复制全文
相关推荐










