barplot in ggplot

2019-05-20 21:44发布

问题:

I'm having problems making a barplot using ggplot. I tried different combinations of qplot and gplot, but I either get a histogram, or it swaps my bars or it decides to use logscaling.

Using the ordinary plot functions. I would do it like

d<-1/(10:1)
names(d) <-paste("id",1:10)
barplot(d)

Thanks

回答1:

To plot a bar chart in ggplot2, you have to use geom="bar" or geom_bar. Have you tried any of the geom_bar example on the ggplot2 website?

To get your example to work, try the following:

  • ggplot needs a data.frame as input. So convert your input data into a data.frame.
  • map your data to aesthetics on the plot using `aes(x=x, y=y). This tells ggplot which columns in the data to map to which elements on the chart.
  • Use geom_plot to create the bar chart. In this case, you probably want to tell ggplot that the data is already summarised using stat="identity", since the default is to create a histogram.

(Note that the function barplot that you used in your example is part of base R graphics, not ggplot.)

The code:

d <- data.frame(x=1:10, y=1/(10:1))
ggplot(d, aes(x, y)) + geom_bar(stat="identity")



标签: r ggplot2