Dataset contains "two friends" and coded "interaction" (all factors). I want to plot the frequency of type of interactions between two friends using a stacked bar. I tried the following code.
Friend1 <- c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B")
Friend2 <- c("1","1","2","2","1","1","2","2","1","1","2","2","1","1","2","2")
Interaction <- c("O","X","D","D","D","X","X","D/R","O","X","D","D","D","X","X","D/R")
df <- data.frame(Friend1, Friend2, Interaction)
df$Friend1 <- as.factor(as.character(df$Friend1))
df$Friend2 <- as.factor(as.character(df$Friend2))
df$Interaction <- as.factor(as.character(df$Interaction))
ggplot(df, aes(fill=Interaction, y=count(Interaction), x=Friend2))
geom_bar(position="fill", stat="identity", color = "white") theme_classic() theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size=1)) theme(strip.background = element_blank()) facet_grid(.~Friend1)
Erorr: Error in UseMethod("count") :
no applicable method for 'count' applied to an object of class "character"
How do I "count" these factors to visualize frequency of interactions?
CodePudding user response:
The issue is that dplyr::count
expects a dataframe as its first argument and returns a dataframe. However, there is no reason to compute the counts as geom_bar
will do that by default, i.e. get rid of y=...
and stat="identity"
:
library(ggplot2)
ggplot(df, aes(fill = Interaction, x = Friend2))
geom_bar(position = "fill", color = "white")
theme_classic()
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size = 1)
)
theme(strip.background = element_blank())
facet_grid(. ~ Friend1)
CodePudding user response:
An alternative visualization using facets per "friends" column may make your counts clearer than a standard stacked bar:
ggplot(df, aes(x = 1, fill = Interaction))
geom_bar(width = 1, color = "white", size = 1, alpha = 0.8)
geom_text(stat = "count", aes(label = after_stat(count)), size = 7,
position = position_stack(vjust = 0.5), color = "white",
fontface = 2)
facet_grid(Friend1 ~ Friend2, switch = "both")
scale_fill_brewer(palette = "Set1")
coord_polar(theta = "y")
labs(x = "Friend1", y = "Friend2")
theme_bw(base_size = 20)
theme(panel.grid = element_blank(),
strip.background = element_blank(),
strip.placement = "outside",
axis.text.x = element_blank(),
panel.border = element_rect(color = "gray90", fill = NA),
panel.spacing = unit(0, "mm"),
axis.text = element_blank(),
axis.ticks = element_blank())