How to draw a basic histogram with X and Y axis in R

别说谁变了你拦得住时间么 提交于 2019-12-25 18:33:29

问题


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 values 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!