Gráficas con Julia usando Plots

Cargamos los paquetes necesarios:

using Plots, StatsPlots, Distributions, Random, RDatasets, DataFrames, PlotThemes
gr() #plotly() #pyplot() #plotlyjs() #pgfplotsx() #unicodeplots()
theme(:ggplot2)

Temas

Para escoger temas de gráficas en Julia, puede usar el paquete PlotThemes. Aquí hay algunos ejemplos de temas populares:

using PlotThemes
theme(:default)      # Tema por defecto
theme(:ggplot2)     # Tema estilo ggplot2
theme(:dark)        # Tema oscuro
theme(:solarized)   # Tema Solarized
theme(:gruvbox)     # Tema Gruvbox

Backends

Julia’s Plots package supports multiple backends for rendering plots. Some of the most commonly used backends include:
- GR: A fast and versatile backend that is the default for Plots.jl. It is suitable for most types of plots and is easy to use.
- PyPlot: A backend that uses Matplotlib, a popular plotting library in Python. It is useful if you are familiar with Matplotlib and want to leverage its features.
- PlotlyJS: A backend that uses Plotly, a JavaScript-based plotting library. It is great for creating interactive plots that can be embedded in web pages.
- PGFPlotsX: A backend that generates LaTeX-compatible plots using the PGFPlots package. It is ideal for creating high-quality plots for academic publications.
- UnicodePlots: A backend that creates plots using Unicode characters, suitable for displaying plots in terminal environments.

Para más información vea: Backends in Plots.jl

Colores en Julia

Vea NamedColors para escoger colores con nombre propio.

La función plot()

La función plot() es la función principal para crear gráficos en Julia usando el paquete Plots. Los argumentos son: - x: Un vector o matriz que representa los valores en el eje x. - y: Un vector o matriz que representa los valores en el eje y. Y los atributos opcionales para personalizar el gráfico:

los atributos más comunes en plot()

  • seriestype: El tipo de gráfico que se desea crear (por ejemplo, :scatter, :line, :bar, etc.).
  • title: El título del gráfico.
  • xlabel: La etiqueta del eje x.
  • ylabel: La etiqueta del eje y.
  • legend: Un booleano que indica si se debe mostrar la leyenda.
  • color: El color de las series de datos.
  • markershape: La forma de los marcadores en gráficos de dispersión.
  • linestyle: El estilo de línea (por ejemplo, :solid, :dash, etc.).
  • linewidth: El grosor de las líneas.
  • size: El tamaño del gráfico (ancho, alto).
  • grid: Un booleano que indica si se debe mostrar la cuadrícula.
  • xlim: Un rango para los límites del eje x.
  • ylim: Un rango para los límites del eje y.
  • layout: Un arreglo que define la disposición de subgráficos.
  • subplot: Un entero que indica en qué subgráfico colocar la serie de datos.
  • savefig: El nombre del archivo para guardar el gráfico.

Creemos conjuntos de datos aleatorios:

Random.seed!(1234) fija la semilla para reproducibilidad.

Random.seed!(1234)
x1 = 5 .*rand(20) .+ 10
x2 = rand(Normal(),200)
x3 = rand(Poisson(3),300)
x4 = rand(10,4);

Una gráfica vacía:

plot()

Inicializa el gráfico de tres series:

plot(3)
plot(x1)           
plot(x4)

Graficación de funciones

plot([sin,cos], 0:0.1:π)     
plot([sin,cos], 0, π)                

Agregar elementos al gráfico de funciones:

title!("Funciones seno y coseno")
xlabel!("Eje x")
ylabel!("Eje y")
plot!(legend=:outerbottom, legendcolumns=2)
annotate!([(π/2, 0, text("sin(x)", :left, 12, :blue)),
            (π/2, 1, text("cos(x)", :right, 12, :orange))]) 

Otra forma:

plot([sin,cos], 0, π,
     title="Funciones seno y coseno",
     xlabel="Eje x",
     ylabel="Eje y",
     legend=:bottomleft,
     legendcolumns=2,
     annotations=[(π/2, 0, text("sen(x)", :left, 12, :blue)),
                  (π/2, 1, text("cos(x)", :right, 12, :red))])       

Atributos para toda la gráfica

plotattr(:Plot)
Defined Plot attributes are:
background_color, background_color_outside, display_type, dpi, extra_kwargs, extra_plot_kwargs, fontfamily, foreground_color, html_output_format, inset_subplots, layout, link, overwrite_figure, plot_title, plot_titlefontcolor, plot_titlefontfamily, plot_titlefonthalign, plot_titlefontrotation, plot_titlefontsize, plot_titlefontvalign, plot_titleindex, plot_titlelocation, plot_titlevspan, pos, show, size, tex_output_standalone, thickness_scaling, warn_on_unsupported, window_title

Atributos para los datos

plotattr(:Series)
Defined Series attributes are:
arrow, bar_edges, bar_position, bar_width, bins, colorbar_entry, connections, contour_labels, contours, extra_kwargs, fill_z, fillalpha, fillcolor, fillrange, fillstyle, group, hover, label, levels, line_z, linealpha, linecolor, linestyle, linewidth, marker_z, markeralpha, markercolor, markershape, markersize, markerstrokealpha, markerstrokecolor, markerstrokestyle, markerstrokewidth, normalize, orientation, permute, primary, quiver, ribbon, series_annotations, seriesalpha, seriescolor, seriestype, show_empty_bins, smooth, stride, subplot, weights, x, xerror, y, yerror, z, z_order, zerror

Atributos para cada gráfica

plotattr(:Subplot)
Defined Subplot attributes are:
annotationcolor, annotationfontfamily, annotationfontsize, annotationhalign, annotationrotation, annotations, annotationvalign, aspect_ratio, background_color_inside, background_color_subplot, bottom_margin, camera, clims, color_palette, colorbar, colorbar_continuous_values, colorbar_discrete_values, colorbar_fontfamily, colorbar_formatter, colorbar_scale, colorbar_tickfontcolor, colorbar_tickfontfamily, colorbar_tickfonthalign, colorbar_tickfontrotation, colorbar_tickfontsize, colorbar_tickfontvalign, colorbar_ticks, colorbar_title, colorbar_title_location, colorbar_titlefontcolor, colorbar_titlefontfamily, colorbar_titlefonthalign, colorbar_titlefontrotation, colorbar_titlefontsize, colorbar_titlefontvalign, extra_kwargs, fontfamily_subplot, foreground_color_subplot, foreground_color_title, framestyle, left_margin, legend_background_color, legend_column, legend_font, legend_font_color, legend_font_family, legend_font_halign, legend_font_pointsize, legend_font_rotation, legend_font_valign, legend_foreground_color, legend_position, legend_title, legend_title_font, legend_title_font_color, legend_title_font_family, legend_title_font_halign, legend_title_font_pointsize, legend_title_font_rotation, legend_title_font_valign, margin, projection, projection_type, right_margin, subplot_index, title, titlefontcolor, titlefontfamily, titlefonthalign, titlefontrotation, titlefontsize, titlefontvalign, titlelocation, top_margin

Atributos para los ejes

plotattr(:Axis)
Defined Axis attributes are:
discrete_values, draw_arrow, flip, foreground_color_axis, foreground_color_border, foreground_color_grid, foreground_color_guide, foreground_color_minor_grid, foreground_color_text, formatter, grid, gridalpha, gridlinewidth, gridstyle, guide, guide_position, guidefontcolor, guidefontfamily, guidefonthalign, guidefontrotation, guidefontsize, guidefontvalign, lims, link, minorgrid, minorgridalpha, minorgridlinewidth, minorgridstyle, minorticks, mirror, rotation, scale, showaxis, tick_direction, tickfontcolor, tickfontfamily, tickfonthalign, tickfontrotation, tickfontsize, tickfontvalign, ticks, unitformat, widen

Ayuda para cada atributo

No olvide ponerlo entre “”

plotattr("linewidth")
:linewidth

Width of the line (in pixels).

Aliases: (:linewidths, :lw, :w, :width).

Type: Real.

`Series` attribute, defaults to `auto`.

Diagrama de caja y bigotes

La función boxplot() pertenece al paquete StatsPlots y se utiliza para crear diagramas de caja y bigotes (box plots) en Julia. Estos gráficos son útiles para visualizar la distribución de un conjunto de datos y para identificar valores atípicos.


::: {#76fa0b8f .cell execution_count=65}
``` {.julia .cell-code}
boxplot(x2, 
title="Boxplot de x2", 
ylabel="Normal", 
xlabel="x2", 
color=:salmon, 
legend=false, 
orientation=:horizontal, 
grid=true, 
linewidth=4, 
whisker_width = 0.2, 
linecolor=:blue , 
label="Boxplot de x2")

:::

Histogramas

histogram(x3, 
title="Histograma de x3", 
xlabel="x3", 
ylabel="Frecuencia", 
color=:chartreuse, 
alpha=0.6  
)

Histograma con áreas iguales

ea_histogram(x3, 
title="Histograma de x3 con áreas iguales", 
xlabel="x3", 
ylabel="Frecuencia", 
color=:deepskyblue, 
alpha=0.6)

Diagrama circular

x = ["Nerds", "Hackers", "Scientists"]
y = [0.4, 0.35, 0.25]
pie(x, y, title = "The Julia Community", l = 0.5)

Superposición de gráficas

x = randn(10^3)
p(x) = 1/sqrt(2pi) * exp(-x^2/2)
b_rango = range(-5, 5, length=21)

histogram(x, label="Experimental", bins=b_rango, normalize=:pdf, color=:blue, alpha=0.5, lw=2)
plot!(p, label="Teórico", lw=3, color=:tomato1)
xlims!(-5, 5)
ylims!(0, 0.4)
title!("Normal distribution, n=1000 ")
xlabel!("x")
ylabel!("P(x)")

Posicionamiento de gráficas

plot(rand(100, 4), layout = (4, 1))
plot(rand(100, 4), layout = (2, 2))
datos = randn(20) .+ 2
scatter(datos, label="points")
boxplot!(datos, label="boxplot", alpha=0.5, color=:blue,  linewidth=2, whisker_width=0.2 , linecolor=:green)

Gráficas a partir de DataFrames con StatsPlots

El formato para graficar con DataFrames es:

@df nombre_del_dataframe plot(datos, atributos…), por ejemplo:

@df df plot(:columna_x, :columna_y, seriestype=:scatter, title="Título", xlabel="Eje X", ylabel="Eje Y", legend=false)

### Creamos un dataFrame de ejemplo:

::: {#50a4d7a2 .cell execution_count=72}
``` {.julia .cell-code}
df = DataFrame(
    Height = rand(150:200, 50),
    Weight = rand(50:100, 50),
    Gender = rand(["Male", "Female"], 50),
    Age = rand(18:60, 50)
)
50×4 DataFrame
25 rows omitted
Row Height Weight Gender Age
Int64 Int64 String Int64
1 199 82 Male 32
2 178 86 Female 32
3 184 50 Male 30
4 157 79 Female 51
5 177 65 Female 47
6 174 75 Male 53
7 180 77 Female 24
8 188 92 Female 42
9 193 87 Male 42
10 157 72 Female 42
11 157 68 Female 38
12 162 78 Male 46
13 153 55 Female 59
39 179 69 Male 29
40 188 98 Male 40
41 156 65 Female 42
42 160 76 Female 27
43 168 60 Male 40
44 181 70 Male 51
45 193 96 Female 53
46 150 59 Female 40
47 184 66 Female 36
48 178 90 Female 31
49 196 57 Male 57
50 175 73 Female 27

:::

@df df scatter(:Height, :Weight,
    group = :Gender,
    xlabel = "Height (cm)",
    ylabel = "Weight (kg)",
    title = "Height vs Weight by Gender",
    markersize = 6,
    alpha = 0.7
)
@df df histogram(:Age,
    bins = 10,
    xlabel = "Age",
    ylabel = "Count",
    title = "Age Distribution",
    color = :orange,
    alpha = 0.6)
@df df boxplot(:Gender, :Weight,
    group = :Gender,           
    xlabel = "Gender",
    ylabel = "Weight (kg)",
    title = "Weight Distribution by Gender",
    color = [:blue :pink],    
    legend = false
)

Gráfica de barras

animals = ["Cat", "Dog", "Bird", "Fish", "Dog", "Cat", "Dog", "Bird", "Cat", "Cat"]

# Count frequencies
using StatsBase
freqs = countmap(animals)

# Separate keys and values
categories = collect(keys(freqs))
counts = collect(values(freqs))

# Bar plot
bar(categories, counts,
    title = "Frequency of Animals",
    xlabel = "Animal",
    ylabel = "Count",
    legend = false,
    bar_width = 0.6,
    color = :skyblue)

A partir de un DataFrame, variable cualitativa

df = DataFrame(Animal = ["Cat", "Dog", "Bird", "Fish", "Dog", "Cat", "Dog", "Bird", "Cat", "Cat"])

# Count frequencies
freqs = countmap(df.Animal)

# Convert to DataFrame for StatsPlots
freq_df = DataFrame(Animal = collect(keys(freqs)), Count = collect(values(freqs)))

# Plot frequencies
@df freq_df bar(:Animal, :Count,
                title = "Frequency of Animals",
                xlabel = "Animal",
                ylabel = "Count",
                legend = false,
                bar_width = 0.6,
                color = :green)

A partir de un DataFrame variable discreta

using DataFrames, StatsBase, StatsPlots

# Example discrete numeric variable: dice rolls
df = DataFrame(Roll = [1, 2, 3, 6, 2, 1, 4, 6, 6, 3, 2, 1, 5, 6, 4, 2])

# Count frequencies
freqs = countmap(df.Roll)

# Convert to DataFrame
freq_df = DataFrame(Roll = collect(keys(freqs)), Count = collect(values(freqs)))

# Bar plot
@df freq_df bar(:Roll, :Count,
                title = "Dice Roll Frequencies",
                xlabel = "Dice Value",
                ylabel = "Count",
                legend = false,
                bar_width = 0.6,
                color = :purple)

Recetas

n = 1000
x = rand(Gamma(2), n)
y = -0.5x + randn(n)
plot1 = marginalhist(x, y, fc = :plasma, bins = 40)

Vea video

Guardar las gráficas

savefig(plot1, "marginalhist.png")  
"/Users/carloslesmes/Dropbox/JULIA/NOTEBOOKS-EP/UMNG:USTA/marginalhist.png"
savefig(plot1, "marginalhist.html")  
"/Users/carloslesmes/Dropbox/JULIA/NOTEBOOKS-EP/UMNG:USTA/marginalhist.html"

Funciones del paquete StatsPlots

@show names(StatsPlots);
names(StatsPlots) = [Symbol("@P_str"), Symbol("@animate"), Symbol("@colorant_str"), Symbol("@df"), Symbol("@gif"), Symbol("@layout"), Symbol("@recipe"), Symbol("@series"), Symbol("@shorthands"), Symbol("@userplot"), :ABGR, :ADIN99, :ADIN99d, :ADIN99o, :AGray, :AGray32, :AHSI, :AHSL, :AHSV, :ALCHab, :ALCHuv, :ALMS, :ALab, :ALuv, :AOklab, :AOklch, :ARGB, :ARGB32, :AXYZ, :AYCbCr, :AYIQ, :AbstractAGray, :AbstractARGB, :AbstractBackend, :AbstractGray, :AbstractGrayA, :AbstractLayout, :AbstractPlot, :AbstractRGB, :AbstractRGBA, :AlphaColor, :Animation, :AxyY, :BGR, :BGRA, :BezierCurve, :CIE1931JV_CMF, :CIE1931J_CMF, :CIE1931_CMF, :CIE1964_CMF, :CIE2006_10_CMF, :CIE2006_2_CMF, :Color, :Color3, :ColorAlpha, :ColorGradient, :ColorPalette, :ColorTypes, :Colorant, :ColorantNormed, :Colors, :DE_2000, :DE_94, :DE_AB, :DE_BFD, :DE_CMC, :DE_DIN99, :DE_DIN99d, :DE_DIN99o, :DE_JPC79, :DIN99, :DIN99A, :DIN99d, :DIN99dA, :DIN99o, :DIN99oA, :Formatted, :Fractional, :GR, :Gray, :Gray24, :GrayA, :HSB, :HSI, :HSIA, :HSL, :HSLA, :HSV, :HSVA, :KW, :LCHab, :LCHabA, :LCHuv, :LCHuvA, :LMS, :LMSA, :Lab, :LabA, :Luv, :LuvA, :MSC, :OHLC, :Oklab, :OklabA, :Oklch, :OklchA, :PlotTheme, :PlotThemes, :PlotUtils, :Plots, :RGB, :RGB24, :RGBA, :RGBX, :RecipeData, :RecipesBase, :Segments, :Shape, :StatsPlots, :Surface, :Transparent3, :TransparentColor, :TransparentGray, :TransparentRGB, :XRGB, :XYZ, :XYZA, :YCbCr, :YCbCrA, :YIQ, :YIQA, :adapted_grid, :add_theme, :aliases, :alpha, :alphacolor, :andrewsplot, :andrewsplot!, :animate, :annotate!, :areaplot, :areaplot!, :arrow, :attr!, :backend, :backend_name, :backend_object, :backends, :bar, :bar!, :barh, :barh!, :barhist, :barhist!, :base_color_type, :base_colorant_type, :bbox, :blue, :boxplot, :boxplot!, :brush, :ccolor, :cdensity, :cdensity!, :center, :cgrad, :chroma, :cie_color_match, :closeall, :color, :color_list, :color_type, :coloralpha, :colordiff, :colormap, :colormatch, :comp1, :comp2, :comp3, :comp4, :comp5, :contour, :contour!, :contour3d, :contour3d!, :contourf, :contourf!, :coords, :cornerplot, :cornerplot!, :corrplot, :corrplot!, :covellipse, :covellipse!, :current, :curve_points, :curves, :curves!, :cvec, :dataviewer, :default, :default_cgrad, :density, :density!, :deuteranopic, :distinguishable_colors, :diverging_palette, :dotplot, :dotplot!, :ea_histogram, :ea_histogram!, :ecdfplot, :ecdfplot!, :errorline, :errorline!, :font, :frame, :gamutmax, :gamutmin, :gaston, :get_color_palette, :gif, :gr, :gray, :green, :grid, :groupedbar, :groupedbar!, :groupedboxplot, :groupedboxplot!, :groupeddotplot, :groupeddotplot!, :groupedhist, :groupedhist!, :groupedviolin, :groupedviolin!, :gui, :hdf5, :heatmap, :heatmap!, :hex, :hexbin, :hexbin!, :histogram, :histogram!, :histogram2d, :histogram2d!, :hline, :hline!, :hspan, :hspan!, :hue, :inline, :inspectdr, :invisible, :isdark, :iter_segments, :lens!, :mapc, :mapreducec, :marginalhist, :marginalhist!, :marginalkde, :marginalkde!, :marginalscatter, :marginalscatter!, :mean_hue, :mesh3d, :mesh3d!, :mov, :mp4, :normalize_hue, :ohlc, :ohlc!, :optimize_datetime_ticks, :optimize_ticks, :palette, :parametric_colorant, :path3d, :path3d!, :pgfplots, :pgfplotsx, :pie, :pie!, :plot, :plot!, :plot3d, :plot3d!, :plot_color, :plotarea, :plotattr, :plotly, :plotlyjs, :plots_heatmap, :plots_heatmap!, :png, :portfoliocomposition, :portfoliocomposition!, :protanopic, :pyplot, :pythonplot, :qqnorm, :qqnorm!, :qqplot, :qqplot!, :quiver, :quiver!, :red, :reducec, :resetfontsizes, :rgb_string, :rgba_string, :rotate, :rotate!, :savefig, :scalefontsize, :scalefontsizes, :scatter, :scatter!, :scatter3d, :scatter3d!, :scatterhist, :scatterhist!, :sequential_palette, :set_theme, :shape_coords, :showtheme, :showtheme!, :spy, :spy!, :stephist, :stephist!, :sticks, :sticks!, :stroke, :surface, :surface!, :test_examples, :testhist, :testhist!, :text, :theme, :theme_palette, :title!, :translate, :translate!, :tritanopic, :twinx, :twiny, :unicodeplots, :violin, :violin!, :vline, :vline!, :vspan, :vspan!, :webm, :weighted_color_mean, :whitebalance, :wireframe, :wireframe!, :with, :wrap, :xaxis!, :xerror, :xerror!, :xflip!, :xgrid!, :xlabel!, :xlims, :xlims!, :xticks, :xticks!, :xyY, :xyYA, :yaxis!, :yerror, :yerror!, :yflip!, :ygrid!, :ylabel!, :ylims, :ylims!, :yticks, :yticks!, :zaxis!, :zerror, :zerror!, :zflip!, :zgrid!, :zlabel!, :zlims, :zlims!, :zscale, :zticks, :zticks!]
dotplot(rand(100), rand(100),
    title = "Dot Plot Example",
    xlabel = "X-axis",
    ylabel = "Y-axis",
    marker = (:circle, 8, :blue),
    legend = false)
heatmap(rand(10,10),
    title = "Heatmap Example",
    xlabel = "X-axis",
    ylabel = "Y-axis",
    color = :viridis,
    legend = true)

Animación

anim = @animate for t in 0:0.1:10
    plot(sin.(0:0.1:2π) .+ 0.1t, 
        ylim=(-2, 2), 
        title="Sine Wave Animation", 
        lw=2, 
        color=:blue)
end

gif(anim, "sine_wave.gif", fps=20)
┌ Info: Saved animation to /Users/carloslesmes/Dropbox/JULIA/NOTEBOOKS-EP/UMNG:USTA/sine_wave.gif
└ @ Plots /Users/carloslesmes/.julia/packages/Plots/Ec1L1/src/animation.jl:156

plotly()

anim = @animate for t in 0:0.05:10
    x = [sin(3u + t) for u in 0:0.01:2π]
    y = [sin(2u) for u in 0:0.01:2π]
    plot(x, y, 
        xlim=(-1.2, 1.2), ylim=(-1.2, 1.2),
        lw=2, color=:red,
        title="Lissajous Curve Animation")
end

# save animation
gif(anim, "lissajous.gif", fps=30)
┌ Info: Saved animation to /Users/carloslesmes/Dropbox/JULIA/NOTEBOOKS-EP/UMNG:USTA/lissajous.gif
└ @ Plots /Users/carloslesmes/.julia/packages/Plots/Ec1L1/src/animation.jl:156
anim = @animate for θ in 0:5:360
    t = 0:0.1:10π
    x = cos.(t)
    y = sin.(t)
    z = t/π
    plot(x, y, z,
        seriestype = :path3d,
        lw = 2,
        color = :blue,
        xlim = (-1.5, 1.5),
        ylim = (-1.5, 1.5),
        zlim = (0, 11),
        camera = (θ, 30),  # rotate camera
        title = "Rotating 3D Helix")
end

# save gif
gif(anim, "helix3d.gif", fps=20)
┌ Info: Saved animation to /Users/carloslesmes/Dropbox/JULIA/NOTEBOOKS-EP/UMNG:USTA/helix3d.gif
└ @ Plots /Users/carloslesmes/.julia/packages/Plots/Ec1L1/src/animation.jl:156