0

I am trying to display the regression coefficients as a bar chart with ggplot.

It concerns a regression analysis of the effects of the child's sex and family size on TV viewing. The regression analysis as found below works, the issue is in plotting the regression coefficients in a bar chart. When trying this, I get the following error message: Error: Aesthetics must be either length 1 or the same as the data (865): x, y.

Does anyone have any idea how to fix this?

tvview_model <- lm(views ~ sex + nrchildren,
                   data = tv_viewing) %>%
coeff_name <- names(tvview_model$coefficients) %>% 
coeff_value <- coefficients(tvview_model) %>% 
ggplot(data = tvview_model, aes(x = coeff_value, y = coeff_name)) +
  geom_bar() 
Andronicus
  • 25,419
  • 17
  • 47
  • 88
Lonneke
  • 11
  • 1
  • Some more information: names of coefficients: "(Intercept)" "sex1" "nrchildren2" "nrchildren3" "nrchildren4" numbers of coefficients: (Intercept) sex1 nrchildren2 nrchildren3 nrchildren4 1.324662195 -0.133497395 0.113001856 -0.004644308 0.018047354 views = numeric variable with hours of tv viewing a day sex = factor with 4 levels: 0 = boy, 1 = girl nrchildren = factor with 4 levels: 1,2,3,4 – Lonneke Jan 24 '20 at 21:59
  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. Even better use a built in data set for your example. – MrFlick Jan 24 '20 at 22:00
  • You might also want to use `broom::tidy()` rather than `coefficients` -- it's much more tidyverse friendly. – MrFlick Jan 24 '20 at 22:02
  • You are both piping the coefficients into `ggplot()` but also defining `data`. You should only do one of those. And you should not use `tvview_model` as the `data`. – Axeman Jan 24 '20 at 22:48

0 Answers0