微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用百分比标记堆栈条形图 数据

如何解决用百分比标记堆栈条形图 数据

我正在尝试用百分比标记堆栈条形图,并以比例结束标记。这是我的代码

            sqlCommand cmd = new sqlCommand("SELECT * FROM[MYTABLE] WHERE([UPN] LIKE '%' + @UPN + '%')",con);
                cmd.Parameters.AddWithValue("UPN",UPNCode);
                con.open();
                DropDownList2.DataSource = cmd.ExecuteReader();
                DropDownList2.DataTextField = "State";
                DropDownList2.DataValueField = "State";

                DropDownList2.DataBind();


                if (DropDownList2.Items.FindByText("AL") != null)
                {
                    DropDownList2.Items.FindByText("AL").Text = "Alabama";
                }

                if (DropDownList2.Items.FindByText("AK") != null)
                {
                    DropDownList2.Items.FindByText("AK").Text = "Alaska";
                }

                if (DropDownList2.Items.FindByText("AZ") != null)
                {
                    DropDownList2.Items.FindByText("AZ").Text = "Arizona";
                } 

graph

解决方法

这是一个潜在的解决方案:

# Load libraries
library(tidyverse)

# Create 'fake' data (minimal reproducible example)
stem_data <- data.frame(Grade = rep(c("A","B","C","P","NP"),2),STEMflag = factor(x = c(rep("STEM",5),rep("NONSTEM",5)),levels = c("STEM","NONSTEM")),percent = c(0.95,0.93,0.90,0.67,0.86,0.05,0.07,0.10,0.33,0.14))
head(stem_data)
#>   Grade STEMflag percent
#> 1     A     STEM    0.95
#> 2     B     STEM    0.93
#> 3     C     STEM    0.90
#> 4     P     STEM    0.67
#> 5    NP     STEM    0.86
#> 6     A  NONSTEM    0.05

# Plot the example data
ggplot(data = stem_data,aes(x = Grade,y = percent,fill = STEMflag,label = paste(percent * 100,"%",sep = ""))) +
  geom_bar(position = "fill",stat = "identity") +
  scale_y_continuous(labels = scales::label_percent(accuracy = 1)) + 
  geom_text(position = position_stack(vjust = 0.5),size = 4)

example_1.png

,

jared's answer 可以进一步改进:

  1. scales::label_percent(accuracy = 1) 可用于格式化geom_text()scale_y_continuous() 中的 种标签一致且无需重复代码立>
  2. geom_bar(stat = "identity") 可以缩写为 geom_col()
# function to format percent labels
lp <- scales::label_percent(accuracy = 1)

library(ggplot2)
ggplot(data = GradeSTEM_data,label = lp(percent))) +
  geom_col(position = "fill") +
  scale_y_continuous(labels = lp) + 
  geom_text(position = position_stack(vjust = 0.5))

enter image description here

数据

GradeSTEM_data <- data.frame(
  Grade = factor(rep(c("A",levels = c("A","NP")),0.14))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。