'Question when drawing a graph in r(dodge or geom_line)
I want to express the frequency of each column (a,b,c,d,e) in a graph of (t) for each group.
I don't know what to do.
As shown in the figure, the data was selected in the form of a data frame, but I don't know what to do when I express it in the next graph.
I tried to extract only the value for a with ggplot, but even this didn't work out. Is there a good way?
Is there a way to express it with lines other than bar graphs?
Help me.
Solution 1:[1]
You can use the following code:
df <- data.frame(t = c("m", "i", "j", "z"),
a = c(300, 20, 15, 500),
b = c(100, 44, 99, 320),
c = c(200, 57, 98, 17),
d = c(150, 52, 122, 666),
e = c(50, 89, 64, 68))
library(tidyverse)
library(reshape)
df %>%
melt(id.vars = "t") %>%
ggplot(aes(x = t, y = value, fill = variable)) +
geom_col(position = "dodge")
Output:
Solution 2:[2]
Pivot the data longer to merge all counts of columns a to e inside just one name and value column, which can be used as dimension aesthetics for ggplot:
library(tidyverse)
data <- tribble(
~t, ~a, ~b,
"m", 300, 100,
"i", 20, 44,
"j", 15, 99
)
data %>%
pivot_longer(-t) %>%
ggplot(aes(t, value, fill = name)) +
geom_col(position = "dodge")
Created on 2022-05-06 by the reprex package (v2.0.0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Quinten |
Solution 2 | danlooo |