R - 如何制作带有所有值标签的堆叠条形图,或可以格式化的 table 文本
R - How to make stacked bar chart with labels for all values, or a table of text that can be formatted
我有一些数据由三列组成 - 代码、结果和类别。我想创建一个堆叠条形图,每个唯一类别都有一个 'bar','bar' 实际上是代码列表,按结果进行颜色编码。本质上是一个带有文本而不是条形的堆叠条形图。如果这不可能,我想创建代码表,按结果进行颜色编码(这在 R 中也可能不可行)。
数据示例:
code<-c("ABC1","ABC2","ABC3","DEF1","DEF2","ABC2","ABC2","XYZ5")
result<-c("Correct","Incorrect","Correct","Blank","Out of date","Correct","Incorrect","Blank")
category<-c("Cat","Cat","Cat","Cat","Dog","Dog","Dog","Fish")
x<-cbind(code,result,category)
x
code result category
[1,] "ABC1" "Correct" "Cat"
[2,] "ABC2" "Incorrect" "Cat"
[3,] "ABC3" "Correct" "Cat"
[4,] "DEF1" "Blank" "Cat"
[5,] "DEF2" "Out of date" "Dog"
[6,] "ABC2" "Correct" "Dog"
[7,] "ABC2" "Incorrect" "Dog"
[8,] "XYZ5" "Blank" "Fish"
编辑:
这是我在想什么的一个做得不好的例子。 (其中绿色正确,红色不正确,灰色为空白,紫色为过时)
在 ggplot 中,尝试使用 'stacked' 颜色编码代码的 'bar-chart' 方法。
#create a dataframe, easier for plotting
x <- data.frame(code,result,category)
#create y-variable
x <- x %>% group_by(category) %>% mutate(y = 1:n())
p1 <- ggplot(x[order(x$code),], aes(x = category, y = y)) +
geom_text(aes(label = code, color = result)) +
theme_bw() + theme(
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)
p1
我有一些数据由三列组成 - 代码、结果和类别。我想创建一个堆叠条形图,每个唯一类别都有一个 'bar','bar' 实际上是代码列表,按结果进行颜色编码。本质上是一个带有文本而不是条形的堆叠条形图。如果这不可能,我想创建代码表,按结果进行颜色编码(这在 R 中也可能不可行)。
数据示例:
code<-c("ABC1","ABC2","ABC3","DEF1","DEF2","ABC2","ABC2","XYZ5")
result<-c("Correct","Incorrect","Correct","Blank","Out of date","Correct","Incorrect","Blank")
category<-c("Cat","Cat","Cat","Cat","Dog","Dog","Dog","Fish")
x<-cbind(code,result,category)
x
code result category
[1,] "ABC1" "Correct" "Cat"
[2,] "ABC2" "Incorrect" "Cat"
[3,] "ABC3" "Correct" "Cat"
[4,] "DEF1" "Blank" "Cat"
[5,] "DEF2" "Out of date" "Dog"
[6,] "ABC2" "Correct" "Dog"
[7,] "ABC2" "Incorrect" "Dog"
[8,] "XYZ5" "Blank" "Fish"
编辑:
这是我在想什么的一个做得不好的例子。 (其中绿色正确,红色不正确,灰色为空白,紫色为过时)
在 ggplot 中,尝试使用 'stacked' 颜色编码代码的 'bar-chart' 方法。
#create a dataframe, easier for plotting
x <- data.frame(code,result,category)
#create y-variable
x <- x %>% group_by(category) %>% mutate(y = 1:n())
p1 <- ggplot(x[order(x$code),], aes(x = category, y = y)) +
geom_text(aes(label = code, color = result)) +
theme_bw() + theme(
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)
p1