stacked bar graph using two numerical columns


Beginner R programmer. I have the following data table & code:

hockeyviz <- quanthockey3 %>%
mutate(Name = fct_reorder(Name, A+G)) %>%
ggplot(aes(x=A+G, y=Name, fill = test)) + geom_col(color="black", fill="lightblue") +
labs(title="Top 10 NHL Point Totals", x="Points", y="Player Name")

I am trying to create a stacked bar graph utilizing goals and assists, however I cannot understand how to go about this when dealing with two numerical columns as opposed to two categorical values. I have researched this relentlessly but cannot find any examples or help.

Any help on this matter is greatly appreciated along with code structure advice. Thank you!

You need to merge goals and assists into one column. You can do this with pivot_longer()

data <- data %>% pivot_longer(., cols = c(G, A)

This will give you two new columns of "name" and "value". So you will then want to change the column name of the new "name" column.

colnames(data)[3] <- "type"

Put whatever number column 'name' was in the brackets, I put a 3 in there as I think it will be column 3 but I am not certain.

Then you can plot by

ggplot(data, aes(x = as.factor(Name), y = value)) +
geom_bar(stat = 'identity', position = 'stack',
aes(fill = type))

Thank you! I was researching pivot_longer() but it was quite confusing to me, so I will have to research it more. My friend that is an experienced coder in other languages helped me to manually create a dataset like this:

Then with this code, I was able to get my desired output:

ggplot(test, aes(x = GA, y = Name, fill = Type)) +

I'm assuming that pivot_longer() does a similar thing but quicker.

pivot_longer() — and its complement, pivot_wider()— are worth getting to know. ggplot(), like other packages in the tidyverse, work best with tidy data.

There's a lot of good information and learning tools about tidyverse packages and tidy data generally over on the tidyverse web site.

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.