恩吉图形画廊¶
在这组示例中,我们将展示 Engee 中最不同类型的图形的外观,以及实现这一效果的方法--数据和代码示例。
正确的图形可以让你以一种非常雄辩而简洁的方式存储或传递正确的信息。图形从变量中获取信息,这些变量必须存在于工作记忆区中(必须在变量窗口中可见)。图形的显示通常通过交互式 ngscript 脚本完成,紧接在相应的代码单元之后。当然,也有例外情况
- 可以在命令行上显示 Unicode 格式的图表,但对于交互式图形图表,这种有限的格式可能只有在特殊图形设计需要时才有必要;
- 图表可以保存到文件存储区,并通过文件浏览器以文件形式打开(有时这很有用)。
最简单、最常用的图形输出命令是Plots
库中的plot()
函数,用于图形输出。
**自动连接 Engee 中的 Plots 库。
尽管如此,在Engee/Julia生态系统中还有许多库可以显示漂亮的绘图,我们将在本演示中探索其中一些库:
*StatsPlots
用于输出复杂的统计图表、
*GMT
或General Mapping Tools
用于绘制地理图。
我们还建议您不要回避能让您创建更丰富、更专业的可视化图形的库,例如
*Makie
用于对复杂数据进行高质量的可视化处理、
*Luxor
- 用于创建矢量二维图形的语言。
输出库创建图形后,会将其传递给图形环境,这里有多个选项:
*gr
环境(默认情况下已启用)可构建快速、节俭和非交互式图形(通过命令gr()
启用),可使用上下文菜单保存这些图形。
*plotly
或plotlyjs
创建一个交互式画布,可使用界面按钮对图形进行缩放、旋转和保存(分别使用plotly()
和plotlyjs()
命令进行切换)。
您还可以选择光栅 (png
) 或矢量 (svg
) 格式输出图形。通过在gr/plotly/plotlyjs
命令中指定参数fmt=:svg
,您将得到一个非常优雅、可缩放的矢量格式图表,但如果图表上有很多元素,尤其是如果图表是交互式的,其输出将需要更多资源。光栅图表 (fmt=:png
) 则另当别论。它们的构建速度更快,重绘时也不需要如此多的资源。
下面是完美图表的其余部分。
现在,欢迎来到图形库!
Pkg.add(["StatsPlots", "WordCloud", "MeshIO", "ColorSchemes", "Colors", "GMT", "Statistics", "StatsBase", "CSV", "Distributions", "Meshes"])
gr()
plot([1,2,3], [1,3,7])
数据分析¶
根据数据表绘制条形图。
using DataFrames, HTTP, CSV;
# Открыть данные из файла
data = sort( CSV.File( "data/city.csv" ) |> DataFrame, ["population"], rev=true );
# (или) Загрузить данные с сервера
#url = "https://raw.githubusercontent.com/hflabs/city/master/city.csv"
#data = sort( CSV.File( HTTP.get(url).body) |> DataFrame, ["population"], rev=true );
bar( first(data, 8).population, label="Население, чел.", xrotation = 30 )
xticks!( 1:8, first(data, 8).address )
使用库StatsPlots
和函数corrplor
研究多元数据的相关性。
using StatsPlots, DataFrames, LaTeXStrings
M = randn( 1000, 4 )
M[:,2] .+= 0.8sqrt.(abs.(M[:,1])) .- 0.5M[:,3] .+ 5
M[:,3] .-= 0.7M[:,1].^2 .+ 2
corrplot( M, label = [L"$x_i$" for i=1:4],
xtickfontsize=4, ytickfontsize=6,
guidefontcolor=:blue, yguidefontsize=15, yguidefontrotation=-45.0 )
函数库中的函数marginalkde
StatsPlots
using StatsPlots
x = randn(1024)
y = randn(1024)
marginalkde(x, x+y)
using DataFrames, Statistics
# Создадим данные
df = DataFrame(Возраст=rand(4), Баланс=rand(4), Должность=rand(4), Зарплата=rand(4))
cols = [:Возраст, :Баланс, :Должность] # Выберем часть данных
M = cor(Matrix(df[!,cols])) # Ковариационная матрица
# График
(n,m) = size(M)
heatmap( M, fc=cgrad([:white,:dodgerblue4]), xticks=(1:m,cols), xrot=90, yticks=(1:m,cols), yflip=true, leg=false )
annotate!( [(j, i, text(round(M[i,j],digits=3), 10,"Arial",:black)) for i in 1:n for j in 1:m] )
正态直方图:函数histogram
using Random
Random.seed!(2018)
x = randn(1000)
y = randn(1000)
z = randn(1000)
histogram(x, bins=20, alpha=0.4, label="A")
histogram!(y, bins=20, alpha=0.6, label="B")
histogram!(z, bins=20, alpha=0.8, label="C")
二维样本分布图:函数histogram2d
x = randn(10^4)
y = randn(10^4)
histogram2d(x, y)
二维直方图的体积图,使用wireframe
using StatsBase
x = randn(10^4)
y = randn(10^4)
h = StatsBase.fit( Histogram, (x, y), nbins=20 )
wireframe( midpoints(h.edges[1]), midpoints(h.edges[2]), h.weights )
组合不同设计的图形
using Random
Random.seed!(1)
plot( Plots.fakedata(100, 12),
layout = 4,
palette = cgrad.([:grays :blues :heat :lightrainbow]),
bg_inside = [:orange :pink :darkblue :black],
seriestype= [:line :scatter :histogram :line] )
以及不同类型的图形:
x = 1:4:250;
y = sin.( 2pi/250 * x );
p1 = plot( x, y, title= "График 1", seriestype=:stem, linewidth=3, legend=false )
p2 = plot( x, y, title= "График 2", seriestype=:scatter, color=:red )
plot!( p2, x .- 10, 0.9y, seriestype=:scatter, color=:black, markersize=2 )
p3 = plot( x, y, title= "График 3", seriestype=:line, color=:green, legend=false )
p4 = plot( x, y, title= "График 4", seriestype=:steppre, color=:black, leg=false )
plot( p1, p2, p3, p4, layout=(2,2), titlefont=font(7), legendfont=font(7) )
Wordcloud:
import Pkg; Pkg.add(["WordCloud"], io=devnull);
using WordCloud, HTTP
# Загрузить текст из файла
content = read( open("data/Википедия - Математика.txt", "r"), String )
# Или загрузить данные с сервера
#url = "https://ru.wikipedia.org/wiki/Математика"
#resp = HTTP.request("GET", url, redirect=true)
#content = resp.body |> String |> html2text
stopwords = ["XVII", "того", "frac"];
stopwords = vcat(stopwords, string.(collect(1:100)));
wc = wordcloud( processtext( content, maxnum=100, stopwords=stopwords, minlength=4 ),
mask=shape(ellipse, 600, 400, color=(0.98, 0.97, 0.99), backgroundcolor=1, backgroundsize=(700, 550)),
masksize=:original, colors=:seaborn_icefire_gradient, angles=[0] ) |> generate!
paint(wc, "$(@__DIR__)/fromweb.svg")
wc
动画¶
使用@animate
命令创建 GIF 动画,该命令循环运行第三方函数,绘制 150 个半径递减、透明度递增的圆。此外,您还可以使用mp4
格式。
@userplot CirclePlot
@recipe function f(cp::CirclePlot)
x, y, i = cp.args
n = length(x)
inds = circshift(1:n, 1 - i)
linewidth --> range(0, 10, length = n)
seriesalpha --> range(0, 1, length = n)
aspect_ratio --> 1
label --> false
x[inds], y[inds]
end
n = 150
t = range(0, 2π, length = n)
x = sin.(t)
y = cos.(t)
anim = @animate for i ∈ 1:n
circleplot(x, y, i)
end
gif(anim, "$(@__DIR__)/anim_fps15.gif", fps = 15)
旋转对象(STL 文件中定义的几何体)
import Pkg; Pkg.add(["Meshes", "MeshIO"], io=devnull);
using Meshes, MeshIO, FileIO
gr();
obj = load( "$(@__DIR__)/data/lion.stl" );
@gif for az in 0:10:359
p = plot( camera = (az, -20), axis=nothing, border=:none, aspect_ratio=:equal, size=(400,400) )
for i in obj
m = Matrix([i[1] i[2] i[3] i[1]])'
if m[1,1] > 0 plot!( p, m[:,1], m[:,2], m[:,3], lc=:green, label=:none, lw=.4, aspect=:equal )
else plot!( p, m[:,1], m[:,2], m[:,3], lc=:gray, label=:none, lw=.4, aspect=:equal )
end
end
end
矩阵和图像输出¶
功能heatmap
include( "$(@__DIR__)/data/peaks.jl" );
(x, y, z) = peaks()
heatmap(x, y, z)
using LaTeXStrings
x = range( -1.3, 1.3, 501 );
y = range( -1.3, 1.3, 501 );
X = repeat( x, outer = [1,501] )
Y = repeat( y', outer = [501,1] )
#C = ones( size(X) ) .* ( 0.360284 + 0.100376*1im );
C = ones( size(X) ) .* ( -0.75 + 0.1im );
Z_max = 1e6; it_max = 50;
Z = Complex.( X, Y );
B = zeros( size(C) );
for k = 1:it_max
Z = Z.^2 .+ C;
B = B .+ ( abs.(Z) .< 2 );
end
heatmap( B,
aspect_ratio = :equal,
cbar=false,
axis=([], false),
color=:jet )
title!( L"Julia Set $(c=0.360284+0.100376i)$" )
从文件中输出插图:图库Images
using Images
load( "$(@__DIR__)/data/640px-Business_Centre_of_Moscow_2.jpg" )
直角坐标图形¶
在直角坐标平面上绘制由向量给出的两个三角函数。
x = 0:0.1:2pi
y1 = cos.(x)
y2 = sin.(x)
plot(x, y1, c="blue", linewidth=3, label="cos")
plot!(x, y2, c="red", line=:dash, label="sin")
title!("Тригонометрические функции")
xlabel!("Угол (рад)")
ylabel!("sin(x) и cos(x)")
# Отдельной командой установим границы осей
plot!( xlims=(0,2pi), ylims=(-2, 2) )
填写图形下的区域(参数fillrange
)
using Distributions
x = range(-3, 3, 100 )
y = pdf.( Normal(0,1), x )
ix = abs.(x) .< 1
plot( x[ix], y[ix], fillrange = zero(x[ix]), fc=:blues, leg=false)
plot!( x, y, grid=false, lc=:black, widen=false )
填充图表 (area
)
x = 1:10;
areaData = x .* rand(10,5) .* 5;
cur_colors = theme_palette(:default)
plot()
for i in 1:size(areaData,2)
plot!( areaData[i,:], fillcolor = cur_colors[i], fillrange = 0, fillalpha=.5 )
end
plot!()
累计填表时间表
x = 1:10;
areaData = x .* rand(10,5);
cur_colors = theme_palette(:default)
plot()
for i in size(areaData,2):-1:1
plot!( sum(areaData[:,1:i], dims=2), fillcolor = cur_colors[i], fillrange = 0, lw=0 )
end
plot!()
带置信区间的图表(参数xerr
和yerr
)
using Random
Random.seed!(2018)
f(x) = 2 * x + 1
x = 0:0.1:2
n = length(x)
y = f.(x) + randn(n)
plot( x, y,
xerr = 0.1 * rand(n),
yerr = rand(n),
marker = (:circle, :red) )
三维图形
t = 0:pi/100:10pi;
x1 = sin.(1 * t)
y1 = cos.(1 * t)
x2 = sin.(2 * t)
y2 = cos.(2 * t)
plot(
plot( x1, y1, t, leg=false, lw=2 ),
plot( x2, y2, t, leg=false, lw=2 )
)
通过参数组合平滑和阶梯图形layout
x = range( 1, 2pi, length=50 )
plot( x, [sin.(x) sin.(x)],
seriestype=[:line :step],
layout = (2, 1) )
三维参数图形
t = range(0, stop=10, length=1000)
x = cos.(t)
y = sin.(t)
z = sin.(5t)
plot( x, y, z )
极坐标图形¶
箭头指向形成螺旋形的点(图形quiver
)
cur_colors = theme_palette(:roma);
th = range( 0, 3*pi/2, 10 );
r = range( 5, 20, 10 );
c = collect(1:10)
X = r .* cos.(th)
Y = r .* sin.(th)
quiver( r.*0, r.*0, quiver=(th,r), aspect_ratio=:equal, proj=:polar,
line_z=repeat(c, inner=4), c=:roma, cbar=false, lw=2 )
功能pie
x = [ "Энтузиасты", "Экспериментаторы", "Ученые" ]
y = [0.4,0.35,0.25]
pie(x, y, title="Кто использует Julia",l = 0.5)
功能polar
θ = range(0, 2π, length=50)
r = 1 .+ cos.(θ) .* sin.(θ).^2
plot(θ, r, proj=:polar, lims=(0,1.5))
极坐标步进图形(图形rose
)
using Random
Random.seed!(2018)
n = 24
R = rand(n+1)
θ = 0:2pi/n:2pi
plot( θ, R, proj=:polar, line=:steppre, lims=(0,1) )
极坐标图形由函数
θ = range( 0, 8π, length=1000 )
fr(θ) = sin( 5/4 * θ )
plot( θ, fr.(θ), proj=:polar, lims=(0,1) )
极坐标气泡图
include( "$(@__DIR__)/data/planetData.jl" );
scatter( angle, distance, ms=diameter, mc = c,
proj=:polar, legend=false,
markerstrokewidth=1, markeralpha=.7 )
title!( "Планеты Солнечной системы" )
离散数据¶
水平条形图 (函数bar
)
ticklabel = string.( collect('а':'м') )
bar( 1:12, orientation=:h, yticks=(1:12, ticklabel), yflip=true )
条形图bar
和groupedbar
using StatsPlots
include( "$(@__DIR__)/data/BostonTemp.jl" );
plots_id = [1,2,3];
groupedbar( hcat([Temperatures[i,:] for i in plots_id]...),
xticks=(1:12, Months),
label = [Years[i] for i in plots_id]',
color = reshape(palette(:tab10)[1:3], (1,3)) )
图表stem
(stem-list)
x1 = range( 0, 2pi, 50 );
x2 = range( pi, 3pi, 50 );
X = [x1, x2];
Y = [cos.(x1), 0.5.*sin.(x2)];
plot( X, Y, line=:stem, marker=:circle )
三维stem
- 图表
X = repeat( range(0,1,10), outer = [1,10] )
Y = repeat( range(0,1,10)', outer = [10,1] )
Z = exp.(X.+Y)
plot( X, Y, Z, line=:stem, color=:skyblue, markercolor=:white, marker=:circle, leg=false )
等高线图¶
include( "$(@__DIR__)/data/flowAroundCylinder.jl" );
(r, theta, x, y, streamline, pressure) = flowAroundCylinder();
plot( x, y, streamline, levels=60, seriestype=:contour,
xlim = [-5,5], ylim=[-5,5], cbar=false, linewidth=2,
leg=false, color=:haline )
(xx,yy) = circle( 0, 0, 1 );
plot!( xx, yy, lw=2, lc=:black )
填充等值线图(层流流线型圆柱体周围的静压)
include( "$(@__DIR__)/data/flowAroundCylinder.jl" );
(r, theta, x, y, streamline, pressure) = flowAroundCylinder();
plot( x, y, pressure, seriestype=:contourf, xlim = [-5,5], ylim=[-5,5], cbar=false, linewidth=1, leg=false )
(xx,yy) = circle( 0, 0, 1 );
plot!( xx, yy, lw=2, lc=:black )
数学函数等值线图
# Подготовим данные
y = x = range( -7, 7, step=0.1 )
z = @. sin(x) + cos(y')
Plots.contour( x, y, z, color=:haline )
曲面和网格¶
参数seriestype=:surface
# Подготовим данные
y = x = range( -7, 7, step=0.1 )
z = @. sin(x) + cos(y')
plot( x, y, z, st=:surface, color=:cool )
参数seriestype=:wireframe
# Подготовим данные
y = x = range( -7, 7, step=0.5 )
z = @. sin(x) + cos(y')
plot( x, y, z, st=:wireframe )
二维函数图
include( "$(@__DIR__)/data/peaks.jl" );
(x,y,z) = peaks();
plot( x, y, z; levels=20, st=:surface )
让我们构建函数 "sombrero "的图形。使用gr()
时,不使用参数hidesurface
。但在使用plotly()
时,参数hidesurface=false
可以同时显示曲面图和等值线图。
x = y = range( -8, 8, length=41 )
f(x,y) = sin.(sqrt.(x.*x+y.*y))./sqrt.(x.*x+y.*y)
# в gr() этот способ позволяет увидеть график поверхности позади графика линий
p = plot( x, y, f, st=:surface, fillalpha=0.7, cbar=false )
plot!( p, x, y, f, st=:wireframe )
# в plotly() есть более удобный синтаксис
#wireframe( x, y, f, hidesurface=false )
点图和气泡图¶
气泡图
using Random: seed!
seed!(28)
xyz = randn(100, 3)
scatter( xyz[:, 1], xyz[:, 2], marker_z=xyz[:, 3],
label="Окружности",
colormap=:plasma, cbar=false,
markersize=15 * abs.(xyz[:, 3]),
xlimits=[-3,3], ylimits=[-3,3]
)
三维点阵图,每个点都有不同的颜色
using Colors, ColorSchemes
cs = ColorScheme([colorant"yellow", colorant"red"])
using CSV, DataFrames
df = DataFrame(CSV.File( "$(@__DIR__)/data/seamount.csv" ))
C = get( cs, df.z, :extrema )
scatter( df.x, df.y, df.z, c=C, leg=false )
带有颜色直方图虚拟空间的三维点阵图
using CSV, DataFrames
df = DataFrame(CSV.File( "$(@__DIR__)/data/seamount.csv" ))
cs = cgrad(:thermal)
C = get( cs, df.x, :extrema )
l = @layout [a{0.97w} b]
p1 = scatter( df.x, df.y, df.z, c=C, leg=false )
p2 = heatmap(rand(2,2), clims=(0,10), framestyle=:none, c=cgrad(cs), cbar=true, lims=(-1,0))
plot(p1, p2, layout=l)
颜色和注释¶
让我们创建一个调色板:
using Images
scheme = rand(RGB, 10)
使用调色板为随机数矩阵着色,并输出为图像:
matrix = rand(1:10, 20, 20)
img = scheme[ matrix ]
创建带有线条和注释的随机点图形:
x = 1:10
y = rand(10)
# Создадим точечный график
scatter(x, y)
# Нанесем вертивальные и горизонтальные линии на график
vline!( [5], color=:red, linestyle=:dash, label=:none )
hline!( [0.5], color=:blue, linestyle=:dot, label=:none )
# Нанесем аннотации на график (работает только в gr())
annotate!( 8, 0.52, text("Горизонтальная линия", :blue, :right, 8))
annotate!( 4.8, 0.7, text("Вертикальная линия", :red, 8, rotation = 90))