Hi! I want to plot a bar graph of a data frame with 1 column corresponding to the height of the bar and another to its color. For example:
julia> df= DataFrame("data"=>rand(10), "color"=>round.(Int,rand(10)*9 .+ 1))
10×2 DataFrame
Row │ data color
│ Float64 Int64
─────┼─────────────────
1 │ 0.94554 5
2 │ 0.486335 4
3 │ 0.946361 4
4 │ 0.585166 7
5 │ 0.673883 8
6 │ 0.190704 8
7 │ 0.740319 9
8 │ 0.441671 5
9 │ 0.952198 5
10 │ 0.199103 8
julia> bar(df.data, color=:BrBG_10)
This gives a bar plot with only 1 color taken from my palette.
How can I use the vector df.color
to index into the palette and get a different color for each bar?
Equivalently, I can pick a different color for each point in a scatter plot:
julia> scatter(1:10,df.data, marker_z= df.color, color=:BrBG_10)
but this doesn’t seem to translate to bar plots.
jling
September 19, 2021, 6:40pm
2
Welcome, fellow HEP user
First you can generate the df with just:
julia> df= DataFrame(data=rand(10), cs=rand(1:10, 10))
10×2 DataFrame
Row │ data cs
│ Float64 Int64
─────┼──────────────────
1 │ 0.312918 7
2 │ 0.349858 8
3 │ 0.80407 3
4 │ 0.702752 3
5 │ 0.384168 1
6 │ 0.302115 2
7 │ 0.727981 8
8 │ 0.99511 10
9 │ 0.0483379 6
10 │ 0.871488 3
The logic of Plots.jl
’s bar is that different groups(color) are on different “column” of the input data, compare:
julia> bar([1 10],
[1 2],
)
julia> bar([1,10],
[1,2],
)
For what you want in this case:
julia> palette = cgrad(:BrBG_10);
julia> bar((1:10)', df.data', color=[palette[i] for i in df.cs]')
2 Likes
jling
September 19, 2021, 6:42pm
3
ksamtsak:
marker_z= df.color,
this is slightly different because this is assuming you’re scattering some 3D data in a 2D plane and using color to represent depth. (or maybe something like data point are in 2D but each point has a temperature represented by color). Bar plot usually doesn’t have this structure
This could be written without a comprehension as:
bar((1:n)', df.data', color=palette[df.cs]')
1 Like
Thank you @jling ! Works perfectly!
Are you at CERN?
1 Like
jling
September 19, 2021, 7:23pm
6
I was at CERN during the summer haha, but now I’m back to the school. Btw, join us at: https://groups.google.com/g/julia-hep
also if you ever work with .root
files again, checkout UnROOT.jl
(sorry for the shameless plug)
1 Like