0

I'm new to ggplot package so please excuse me if this is regarding basic matters

I've set up the code below but the labels of x-axis are messed up. It doesn't match with the data frame's data, rather randomized.

for the picture. I think Start_Profit comes first then ProductionCost and SalesCost.

Did I make missing sth important?

ggplot_image

library(ggplot2)

plot_data <- data.frame(
 items = c("Start_Profit","ProductionCost","SalesCost","End_Profit"),
 diff = c(50,20,-30,40),
 type = c("Net","Increase","Decrease","Net"),
 start = c(0,50,70,40),
 end = c(50,70,40,0)
)

plot_data$id <- seq_along(plot_data$diff)


ggplot(plot_data[1:3,], aes(fill = type)) + geom_rect(aes(x = items,
                                                    xmin=id-0.45, xmax=id+0.45,
                                                    ymin = end, ymax=start))
James
  • 1
  • 3
  • `ggplot2` uses the order of the factor, which by default is alphabetical. See the linked duplicate for how to change this. – Axeman Jul 13 '18 at 09:40
  • 1
    Passing `x = items` to `geom_rect` doesn't do anything, it doesn't have this option. You probably want rename your x-axis with `scale_x_discrete`. – pogibas Jul 13 '18 at 09:41
  • @Axeman, thank you and one more question. Doesn’t R care the pairing between values and their labels? in this case the plot shows strange pairs of label and value beside of the order of x-axis. Do you know why this happened, the misleading plot? – James Jul 13 '18 at 10:17
  • It does, but you are passing an `x` aesthetic to the `geom_rect` layer (which generates a warning!), and that is messing up your labels. `geom_rect` works with a continuous x axis, not a discrete one. – Axeman Jul 13 '18 at 11:31
  • @Axeman, Thank you it helped a lot – James Jul 16 '18 at 02:14
  • @PoGibas, as id is continous value, I think scale_x_continuous solve the issue, `ggplot(plot_data, aes(fill = type)) + geom_rect(aes(xmin=id-0.45, xmax=id+0.45,ymin = end, ymax=start)) + scale_x_continuous(breaks=plot_data$id,labels=plot_data$items)` – James Jul 16 '18 at 02:15

0 Answers0