问题
I want to make a simple histogram which involves two vectors ,
values <- c(1,2,3,4,5,6,7,8)
freq <- c(4,6,4,4,3,2,1,1)
df <- data.frame(values,freq)
Now the data.farame
df
consists the following values :
values freq
1 4
2 6
3 4
4 4
5 3
6 2
7 1
8 1
Now I want to draw a simple histogram, in which value
s are on the x axis and freq
is on y axis. I am trying to use the hist
function, but I am not able to give two variables. How can I make a simple histogram from this data?
回答1:
using ggplot2:
library(ggplot2)
ggplot(df, aes(x = values, y = freq)) +
geom_bar(stat="identity")
回答2:
Since you have the frequencies already, what you really want is a bar plot:
barplot(df$freq,names.arg=df$values)
If you've got your heart set on using hist
, you should do:
hist(rep(df$values,df$freq))
Please read ?barplot
and ?hist
for further plotting options.
Also, because I'm somewhat of a zealot, I think the code looks cleaner if you use data.table
:
library(data.table)
setDT(df) #convert df to a data.table by reference
df[,barplot(freq,names.arg=values)]
and
df[,hist(rep(values,freq))]
来源:https://stackoverflow.com/questions/31639990/how-to-draw-a-basic-histogram-with-x-and-y-axis-in-r