1

I tried to smaller the font size of the x-axis in the barplot, using cex.lab. However, there are no changes, regardless of how I play with the numbers. Hence, I am wondering what has gone wrong in my code, as shown below.

car$Brand <- factor(car$Brand) %>% fct_infreq()

plot(carl$Brand, las=2, col= "dark blue", ylim=c(0,35), cex.lab=0.2)

enter image description here

Additionally, I would like to ask how to fade the color from dark color to light color (from dark blue to light blue) as the data value are getting smaller

Many thanks

adam
  • 51
  • 4
  • Welcome to SO. Please provide your data in `dput()` format. You can visit [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). For changing axis fonts use `cex.axis = 0.5` with `cex=0.5` – UseR10085 Jan 02 '23 at 07:21

2 Answers2

2

You must set both cex and cex.axis to change the axis labels sizes.
As for the colors, colorRampPalette returns an interpolating function between two limits.

set.seed(2022)
car <- data.frame(
  Brand = sample(LETTERS[10:1], 1e3, TRUE, prob = (1:10)/10)
)

car$Brand <- factor(car$Brand) |> forcats::fct_infreq()
ncolors <- length(unique(car$Brand))
fcolors <- colorRampPalette(c("dark blue", "light blue"))
fcolors(ncolors)
#>  [1] "#00008B" "#131895" "#26309F" "#3948A9" "#4C60B3" "#6078BD" "#7390C7"
#>  [8] "#86A7D1" "#99C0DB" "#ADD8E6"

plot(car$Brand, las=2,
     col= fcolors(ncolors),
     cex = 0.5, cex.axis = 1)

Created on 2023-01-02 with reprex v2.0.2

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
1

one approach:

  • save default graphic parameters for later restore:
old_pars <- par()
  • set character expansion for axis:
par(cex.axis = .5)
  • map factor value to color (using {scales} for convenience):
library(scales)
my_colors <- scales::col_numeric('Blues', domain = as.integer(car$Brand),
                                 reverse = TRUE)(as.integer(car$Brand))
  • plot
plot(car$Brand, las=2, col= my_colors)
  • reset graphical parameters:
par(old_pars)

Please note that, while technically possible, using several visual cues for the same property (here: bar height and color for Brand count) is likely to bias the viewer's impression: https://en.wikipedia.org/wiki/Chartjunk


Edit

To truly map colours to values (so that e.g. tied frequency ranks share the same colour):

  • example data:
df <- data.frame(Brand = rep(c('Volvo', 'Mercedes-Benz', 'Peugeot', 'Audi'), times = c(12, 12, 5, 2)))
  • summarise brands by frequency:
brand_count <- table(car$Brand) |> sort(decreasing = TRUE)
  • create colour scale:
my_colors <-  scales::col_numeric('Blues', domain = brand_count)
  • barplot frequency table:
barplot(brand_count, col = my_colors(as.integer(brand_count)))

(barplot being implicity called by plot(some_factor) when the y-value is numeric like e.g. frequency of the factor level)

output: enter image description here

I_O
  • 4,983
  • 2
  • 2
  • 15