Home > Net >  Create a color vector from a dataframe in R and create a barplot
Create a color vector from a dataframe in R and create a barplot

Time:11-11

I have below dataframe:

City Cost
Brisbane 1657
Melbourne 7583
Victoria 5738
Sydney 9274
NSW 5938
Adelaide 8223

I want to create a vector from this dataframe by giving different colors to each city. Then I need to plot a barplot City~Cost using that given colors.

I tried below code to create the vector:

cv <- dColorVector(df$City, colorScale = "plasma")

But get an error: could not find function "dColorVector"

Pls help!

CodePudding user response:

It looks like you can easily get the same result directly the viridis package, which is what dColorVector uses anyway.

library(viridis)

cv <- plasma(length(df$City))

cv
#> [1] "#0D0887FF" "#6A00A8FF" "#B12A90FF" "#E16462FF" "#FCA636FF" "#F0F921FF"

barplot(Cost ~ City, data = df, col = cv)

enter image description here

  • Related