R Histogram from Frequency Table

Plot a histogram for a frequency table in R- ggplot2

First make your data from wide to longer using pivot_longer. After that you can create a stacked barplot like this:

library(ggplot2)
library(dplyr)
library(tidyr)
df_1 %>%
pivot_longer(-ref) %>%
ggplot(aes(x = ref, y =value, fill = name)) +
geom_bar(stat = "identity", position = "stack")

Output:

Sample Image

Make Frequency Histogram for Factor Variables

It seems like you want barplot(prop.table(table(animals))):

Sample Image

However, this is not a histogram.

How to create histogram table? R

Use barplot, since you already got your frequencies?

df <- read.table(header=T, text="
x freq
1 Buick 80
2 Cadillac 80
3 Chevrolet 320
4 Pontiac 150
5 SAAB 114
6 Saturn 60")
df
barplot(df$freq, names.arg = df$x)

plot histogram of frequency of values occurring in a column based on list of values from another file

You can easily calculate the frequency of V2 (in l2) with the function count() from the library dplyr.

library(dplyr)
count(l2, V2)

# V2 n
# 1 A1 2
# 2 C 1
# 3 D 1
# 4 E1 2

Then, transform l1 to a dataframe, and merge it with the result of the count in order to keep all the levels in l1:

l1 <- c("A1", "A2", "B-1", "C", "D", "E1")
left_join(data.frame(V2 = l1), count(l2, V2), by = 'V2')

# V2 n
# 1 A1 2
# 2 A2 NA
# 3 B-1 NA
# 4 C 1
# 5 D 1
# 6 E1 2

Then you can divide by number of observations (6 in this case) to calculate the proportion, and you can build an histogram (with ggplot2 for instance, or with barplot() if your prefer).

library(ggplot2)
left_join(data.frame(V2 = l1), count(l2, V2), by = 'V2') %>%
ggplot(aes(x = V2, y = n)) +
geom_col()


Related Topics



Leave a reply



Submit