python发散型条形图代码
时间: 2023-10-13 08:56:25 浏览: 113
python散点图代码
以下是使用Python绘制发散型条形图的代码示例:
```python
# 导入所需的库
import pandas as pd
import matplotlib.pyplot as plt
# 准备数据
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")
x = df.loc\[:, \['mpg'\]\]
df\['mpg_z'\] = (x - x.mean()) / x.std()
df\['colors'\] = \['red' if x < 0 else 'green' for x in df\['mpg_z'\]\]
df.sort_values('mpg_z', inplace=True)
df.reset_index(inplace=True)
# 绘制图形
plt.figure(figsize=(14, 10), dpi=80)
plt.hlines(y=df.index, xmin=0, xmax=df.mpg_z, color=df.colors, alpha=0.4, linewidth=5)
# 图形装饰
plt.gca().set(ylabel='$Model$', xlabel='$Mileage$')
plt.yticks(df.index, df.cars, fontsize=12)
plt.title('Diverging Bars of Car Mileage', fontdict={'size': 20})
plt.grid(linestyle='--', alpha=0.5)
plt.show()
```
这段代码使用了matplotlib库来绘制发散型条形图。首先,我们导入所需的库,然后准备数据。数据来自于mtcars数据集,我们计算了每个汽车型号的mpg_z值,并根据mpg_z的正负值给条形图上色。然后,我们按照mpg_z的大小对数据进行排序,并重置索引。最后,我们使用plt.hlines函数绘制发散型条形图,并进行图形装饰,包括添加标签、标题和网格线。最终,使用plt.show()函数显示图形。
#### 引用[.reference_title]
- *1* [你了解matplotlib吗?对称条形图和发散型条形图篇](https://blog.csdn.net/yoggieCDA/article/details/106231634)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [Python使用matplotlib可视化发散型条形图、发散条形图(Diverging Bars)是一种可以同时处理负值和正值的...](https://blog.csdn.net/zhongkeyuanchongqing/article/details/122931290)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [4-02-3 Matplotlib 散点图、发散型条形图、饼图](https://blog.csdn.net/m0_50614038/article/details/124243732)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文