将全局标题添加到 Plots.jl 个子图

Adding global title to Plots.jl subplots

我想使用 Plots.jl 为一组子图添加全局标题。

理想情况下,我会做类似的事情:

using Plots
pyplot()
plot(rand(10,2), plot_title="Main title", title=["A" "B"], layout=2)

但是,根据 Plots.jl documentationplot_title 属性尚未实现:

Title for the whole plot (not the subplots) (Note: Not currently implemented)

同时,有什么办法解决吗?

我目前正在使用 pyplot 后端,但我并没有特别依赖它。

subplotsPlot 类型的字段,每个子图都有一个名为 :attr 的字段,您可以修改和重新 display() 该图。尝试以下操作:

julia> l = @layout([a{0.1h} ;b [c; d e]])
Plots.GridLayout(2,1)

julia> p = plot(randn(100,5),layout=l,t=[:line :histogram :scatter :steppre :bar],leg=false,ticks=nothing,border=false)

julia> p.subplots
5-element Array{Plots.Subplot,1}:
 Subplot{1}
 Subplot{2}
 Subplot{3}
 Subplot{4}
 Subplot{5}

julia> fieldnames(p.subplots[1])
8-element Array{Symbol,1}:
 :parent     
 :series_list
 :minpad     
 :bbox       
 :plotarea   
 :attr       
 :o          
 :plt

julia> for i in 1:length(p.subplots)
           p.subplots[i].attr[:title] = "subtitle $i"
       end

 julia> display(p)

您现在应该会在每个 subplot

中看到一个标题

当使用 pyplot 后端时,您可以使用 PyPlot 命令来更改 Plots 图形,参见。 Accessing backend specific functionality with Julia Plots.

要为整个图形设置标题,您可以这样做:

using Plots
p1 = plot(sin, title = "sin")
p2 = plot(cos, title = "cos")
p = plot(p1, p2, top_margin=1cm)
import PyPlot
PyPlot.suptitle("Trigonometric functions")
PyPlot.savefig("suptile_test.png")

需要显式调用 PyPlot.savefig 才能看到 PyPlot 函数的效果。

请注意,使用 PyPlot 界面所做的所有更改都将在您使用 Plots 功能时被覆盖。

这有点 hack,但对于后端来说应该是不可知的。基本上创建一个新图,其中唯一的内容是您想要的标题,然后使用 layout 将其添加到顶部。这是使用 GR 后端的示例:

# create a transparent scatter plot with an 'annotation' that will become title
y = ones(3) 
title = Plots.scatter(y, marker=0,markeralpha=0, annotations=(2, y[2], Plots.text("This is title")),axis=false, grid=false, leg=false,size=(200,100))

# combine the 'title' plot with your real plots
Plots.plot(
    title,
    Plots.plot(rand(100,4), layout = 4),
    layout=grid(2,1,heights=[0.1,0.9])
)

生产:

Plots.jl 的更新版本支持 plot_title 属性,该属性为整个情节提供标题。这可以与各个地块的各个标题相结合。

using Plots   

layout = @layout [a{0.66w} b{0.33w}]
LHS = heatmap(rand(100, 100), title="Title for just the heatmap")
RHS = plot(1:100, 1:100, title="Only the line")
plot(LHS, RHS, plot_title="Overall title of the plot")

或者,您可以直接为现有绘图设置标题。

p = plot(LHS, RHS)
p[:plot_title] = "Overall title of the plot"
plot(p)