plotjuliajulia-plots

Add table inside plot Julia


I have the following bar plot:

using Plots, DataFrames

Plots.bar(["A", "B", "c"],[6,5,3],fillcolor=[:red,:green,:blue], legend = :none)

Output:

enter image description here

I would like to add a simple small table inside to plot in the top right corner. The table should have the following values of the dataframe:

df = DataFrame(x = ["A", "B", "c"], y = [6,5,3])

3×2 DataFrame
 Row │ x       y     
     │ String  Int64 
─────┼───────────────
   1 │ A           6
   2 │ B           5
   3 │ c           3

So I was wondering if anyone knows how to add a simple table to a Plots graph in Julia?


Solution

  • You can use the following:

    using Plots, DataFrames
    
    df = DataFrame(; x=["A", "B", "c"], y=[6, 5, 3])
    plt = Plots.bar(
        df[!, :x], df[!, :y]; fillcolor=[:red, :green, :blue], legend=:none, dpi=300
    )
    Plots.annotate!(
        1,
        4,
        Plots.text(
            replace(string(df), ' ' => '\u00A0'); family="Courier", halign=:left, color="black"
        ),
    )
    
    Plots.savefig("plot.svg")
    

    Which gets you the following plot (after conversion to PNG for uploading to StackOverflow):

    Plot

    Note that we have to replace space characters with '\u00a0', non-breaking space, to prevent multiple consecutive spaces from being collapsed by the SVG (SVG‘s collapse consecutive spaces by default).