在 R 中绘制具有默认值的水平条形图
Plot a horizontal bar chart with default values in R
我有一个这样的DF:
df_test <- data.frame (ID = c(88888, 99999),
Cluster1 = c(0, 1),Cluster2 = c(0, 2),Cluster3 = c(1, 3)
)
ID Cluster1 Cluster2 Cluster3
1 88888 0 0 1
2 99999 1 2 3
现在我想要一个水平条形图,其中的簇位于 y 轴上。所有条形应该从 0-3(最小 - 最大)变化,因为这是簇的范围。作为颜色,我想要三个层次,0-1 红色,1-2 黄色和 2-3 绿色。然后,来自 DF 的值应在整个条形图上显示为箭头或线条。 ggplot2 在某种程度上可能吗?
您可以在此处使用 geom_col
以下示例:https://ggplot2.tidyverse.org/reference/geom_bar.html
library(dplyr)
library(tidyr)
library(ggplot2)
首先,整理数据:
df <- df_test %>% pivot_longer(cols = 2:4,
names_to = "Cluster",
values_to = "value")
保留每个簇中最大的一个来制作条形图:
df <- df %>% group_by(Cluster) %>%
filter(value == max(value)) %>%
ungroup() %>%
# identify color scheme:
mutate(cols = case_when(value <=1 ~ "red",
value > 1 & value <= 2 ~ "yellow",
value > 2 ~ "green"))
ggplot(df) + geom_col(aes(x = value, y=Cluster, fill = Cluster)) +
scale_colour_manual(
values = df$cols,
aesthetics = c("colour", "fill")
)
我有一个这样的DF:
df_test <- data.frame (ID = c(88888, 99999),
Cluster1 = c(0, 1),Cluster2 = c(0, 2),Cluster3 = c(1, 3)
)
ID Cluster1 Cluster2 Cluster3
1 88888 0 0 1
2 99999 1 2 3
现在我想要一个水平条形图,其中的簇位于 y 轴上。所有条形应该从 0-3(最小 - 最大)变化,因为这是簇的范围。作为颜色,我想要三个层次,0-1 红色,1-2 黄色和 2-3 绿色。然后,来自 DF 的值应在整个条形图上显示为箭头或线条。 ggplot2 在某种程度上可能吗?
您可以在此处使用 geom_col
以下示例:https://ggplot2.tidyverse.org/reference/geom_bar.html
library(dplyr)
library(tidyr)
library(ggplot2)
首先,整理数据:
df <- df_test %>% pivot_longer(cols = 2:4,
names_to = "Cluster",
values_to = "value")
保留每个簇中最大的一个来制作条形图:
df <- df %>% group_by(Cluster) %>%
filter(value == max(value)) %>%
ungroup() %>%
# identify color scheme:
mutate(cols = case_when(value <=1 ~ "red",
value > 1 & value <= 2 ~ "yellow",
value > 2 ~ "green"))
ggplot(df) + geom_col(aes(x = value, y=Cluster, fill = Cluster)) +
scale_colour_manual(
values = df$cols,
aesthetics = c("colour", "fill")
)