前言:
如今朋友们对“python打印星星金字塔”大体比较注意,我们都想要分析一些“python打印星星金字塔”的相关知识。那么小编同时在网上汇集了一些有关“python打印星星金字塔””的相关内容,希望小伙伴们能喜欢,同学们快快来了解一下吧!以下内容来自百度百科:
金字塔图表是由两套柱状统计图表相对组合而成,因其形似金字塔而得名。
数据准备
小贴士:为便于后续制作,对 % Female 做了特殊处理(乘-1),这也是最重要的技巧。
以下分别通过Excel、R ggplot2、Python matplotlib进行制图。
Excel
1)选中数据,插入“簇状条形图”
2)修改标题,删除水平轴,选中垂直轴,选择“逆序类别”,标签位置选择“低”
3)添加标签,% Female 标签数字格式代码改为“;##.##%;”
4)选中 % Male,调整系列重叠和间隙宽度,至此完成制作。
R ggplot2
library(readxl)library(ggplot2)library(dplyr)library(tidyr)library(magrittr)df <- read_xlsx("population.xlsx")df$group <- as.factor(nrow(df):1)df1 <- df %>% select(group, `% Male`, `% Female`) %>% pivot_longer(cols = 2:3, names_to = "Gender", values_to = "Rate") df1ggplot(data = df1, aes(x = group, y = Rate, fill = Gender)) + geom_bar(stat = "identity") + scale_y_continuous(labels = abs, limits = c(-0.05, 0.05)) + scale_x_discrete(breaks = df$group, labels = df$Age) + labs(title = "China Population (2020)", x = NULL, y = "Rate") + # geom_label() + geom_text(aes(label = paste0(round(abs(Rate)*100,2), "%"), y = Rate), position = "dodge") + coord_flip() + theme_light()Python matplotlib
import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsdf = pd.read_excel("population.xlsx", sheet_name=0)df.head()bar_plot = sns.barplot(y = "Age", x = "% Male", color = "red", data = df)bar_plot = sns.barplot(y = "Age", x = "% Female", color = "blue", data = df)bar_plot.set(xlabel="Rate", ylabel=None, title = "China Population (2020)")
版权声明:
本站文章均来自互联网搜集,如有侵犯您的权益,请联系我们删除,谢谢。
标签: #python打印星星金字塔