# bar chart, ggplot formula

Hi Community,

I am looking to get a bar chart viz function right such as: ggplot(data, aes(x=?)) + geom_bar() The x-axis should indicate 3 distinct columns a, b, and c where each has a total value (a=8, b=10, c=13). In the formula where I wrote x=?, how can x represent all 3 columns total? Thanks,

Can you provide a reproducible example?

2 Likes

This is the ggplot function I am trying to get right. ggplot(data, aes(x=?))+ geom_bar() I want x to represent 3 different values such as: value a, which is equal to 8, value b = 10, and value c = 13. How can I represent all 3 on the formula (x=?).

Can you provide some data?

I already presented data. I want to have 3 columns on x-axis. column 'a' has a value of 8, column 'b' has 10, and column 'c' has 13. This is the formula I am trying to include the 3 columns on x: ggplot(data, aes(x=...)) + geom_bar()

That's code, not data. Have a look at the article and make your post reproducible.

Try this link and check out gold, silver, and bronze medals. Those 3 columns (each totaled) need to be visualized as a bar chart, on x-axis

``````library(tidyverse)

mydata <- data.frame(
name=letters[1:3],
value =c(8,10,13)
)

ggplot(mydata, aes(x=name,
y=value)) + geom_col()
``````

you may benefit from studying this useful book.

2 Likes

Thanks buddy! In the formula where you wrote: name=letters[1:3], where do the 3 columns names fit in? I have column named: gold, silver, and bronze

letters is simply a built-in to R vector of the lowercase letters.
You can substitute for any size 3 vector given that the data.frame is 3 entries.
For general info on what vectors are in R , try a resource like
20 Vectors | R for Data Science (had.co.nz)

1 Like

You need to transform your data into a longer format if you have the values you want plotted in different columns. ggplot2 likes working with long formatted data, so learning data transformations is key to ggplot success.

``````library(tidyverse)

# Create the data
data <- tibble(
a = 8,
b = 10,
c = 13
)

data
#> # A tibble: 1 x 3
#>       a     b     c
#>   <dbl> <dbl> <dbl>
#> 1     8    10    13

# Make the data long,
# Transforms the data to something ggplot likes
data_long <- data %>%
pivot_longer(everything())

data_long
#> # A tibble: 3 x 2
#>   name  value
#>   <chr> <dbl>
#> 1 a         8
#> 2 b        10
#> 3 c        13

ggplot(data_long) +
geom_bar(aes(x = name,
y = value),
stat = "identity") # use value from the data
`````` Created on 2021-08-19 by the reprex package (v2.0.0)

2 Likes

Thanks! This is truly the answer I was seeking.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.