How to tweak dodge bar plot's label position of AOG

math4mad
Mon, 01 Jan 2024 01:26:33 +0000
Visualization

I want to clone this chart :
Views about AI’s impact on society in the next 20 years, 2021

here is my code

using   Tidier, DataFrames, CSV, AlgebraOfGraphics, Pipe

countrys = ["Japan", "China", "Germany", "France"]
cats = [
  "Mostly help",
  "Neither",
  "Refused - help/harm question",
  "Don't have an opinion, Don't know - help/harm question",
  "Mostly harm"
]

df = @pipe CSV.File("./data/views-ai-impact-society-next-20-years.csv") |>
      DataFrame |>
      coalesce.(_, 0)
rename!(
  df,
  "Mostly help" => :x1,
  "Neither" => :x2,
  "Refused - help/harm question" => :x3,
  "Don't have an opinion, Don't know - help/harm question" => :x4,
  "Mostly harm" => :x5
)

df2 = @chain df begin
  @filter(Entity in ["Japan", "China", "Germany", "France"])
  @filter(Year == 2021)
  @select(Entity, x1, x2, x3, x4, x5)
  @pivot_longer(_, x1:x5, names_to = opinion, values_to = counts)
  @mutate(
    opinion = case_when(
      opinion == "x1" => "Mostly help",
      opinion == "x2" => "Neither",
      opinion == "x3" => "Refused",
      opinion == "x4" => "Don't have an opinion",
      opinion == "x5" => "Mostly harm"
    )
  )
end

axis = (
  width = 600,
  height = 200,
  xticklabelrotation = pi / 8,
  title = "Opinion on  AI development in next 20 years",
  yticks = (1:4, countrys),
  xticklabelsvisible = false,
  xgridvisible = false,
  xticksvisible = false,
  ylabel = "Country",
  xlabel = "Percent"
)
data_layer = data(df2)
mapping_layer = mapping(:Entity, :counts; color = :opinion, stack = :opinion)
visual_layer = visual(
  BarPlot;
  direction = :x,
  flip_labels_at = 0.1,
  bar_labels = :y,
  label_color = :white
)
draw(
  data_layer * mapping_layer * visual_layer;
  axis = axis,
  legend = (
    position = :right,
    titleposition = :top,
    framevisible = false,
    padding = 1
  )
)

use bar_labels can get label but position is not ok ,better be at center, how to tweak this issue, by the way , delete total precent

In short , I want to put numbers in the middle

1 post - 1 participant