Home > front end >  Trying to plot a bar chart in R with "character" on x axis and "factors" on y ax
Trying to plot a bar chart in R with "character" on x axis and "factors" on y ax

Time:05-18

Degrees: ME, BE, EMPS, NAME, EIM, EC, MA, MH, OE, RC, CFS, AS

Income: 73926, 97410, 74179, 75635, 78866, 54000, 44800, 45000, 46300, 46400, 46500, 47000

structure(list(Degree = c("ME", "BE", "EMPS", "NAME", "EIM", "Ec", "MA", "MH", "OE", "RC", "CFS", "AS"), Income = c(73926, 97410, 74179, 75635, 78866, 54000, 44800, 45000, 46300, 46400, 46500, 47000)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -12L))

''' barplot(data$Degrees, data$Income) '''

Newbie to R here. I am trying to replicate the bar chart below, but in R. Really struggling with this as all attempts end with the error 'argument is not numeric or logical'. Unsure what to do next and any advice would be appreciated.

enter image description here

CodePudding user response:

Look for ggplot2 package information

Tryed to create the code strucutre so you can edit some characteristc like texts size and etc:

ggplot(df) 
        geom_col(aes(x = Degree, 
                     y = Income),
                 fill = "blue",
                 width = 0.7) 
        theme_classic()  
        ggtitle("Graph title",
                subtitle = "Subtitle") 
        labs(x = "X axis title",
             y = "Y axis title") 
        theme(axis.title = element_text(size = 15, face = "bold"),
              axis.text = element_text(size = 10),
              plot.title = element_text(size = 20, hjust = 0.5),
              plot.subtitle = element_text(size = 15, hjust= 0.5))
    

enter image description here

CodePudding user response:

You might also try:

barplot( df$Income ~ df$Degree, col = "blue")

enter image description here

I wasn't sure how to do this (I mostly use ggplot2, not base R plots), but here's what I did to figure it out, in case it helps for any future endevours.

  1. I selected the word barplot in the code and clicked F1 to get the help for the function. You can also type ?barplot in the console.

  2. R help files have a certain format that might take some getting used to. The "Usage" section on the top notes the arguments it takes. The "Examples" section at the bottom typically shows the normal way(s) to use the function. It shows barplot(GNP ~ Year, data = longley) which has the same syntax as some other R functions like lm and plot, where y ~ x means, depending on the function, "regress or plot y as a function of x."

  • Related