Reputation:
I am struggling to understand how I can get the following data into a histogram:
NSP <- c(1380, 6003, 1827, 661, 331, 156, 97, 73, 58)
hist(NSP)
Each number should represent one bar in the exactly same order. I tried to use ggplot but failed to get the frequencies on the Y axis.
Many thanks in advance!
Upvotes: 2
Views: 140
Reputation: 9560
If you are trying to use ggplot2
, then you likely want geom_col
. Note that you will need to specify x-positions for the bars. Here, I am just specifying them as 1:length(NSP)
using seq_along
:
ggplot(
mapping = aes(y = NSP
, x = seq_along(NSP))) +
geom_col() +
scale_x_continuous(breaks = seq_along(NSP))
If you have other labels for the breaks, you can specify them, e.g.:
ggplot(
mapping = aes(y = NSP
, x = seq_along(NSP))) +
geom_col() +
scale_x_continuous(breaks = seq_along(NSP)
, labels = LETTERS[seq_along(NSP)])
Note, however, that ggplot
generally works much more smoothly when your data are in a data.frame. This may be a more flexible approach for you, and allow more succinct naming of the column locations (e.g., if they are not evenly spaced, you could have one column for the actual location, and one column for the label).
NSP_df <- data.frame(Location = LETTERS[seq_along(NSP)]
, Count = NSP)
ggplot(
NSP_df
, aes(y = Count
, x = Location)) +
geom_col()
Upvotes: 2