using Plots, StatsPlots, Distributions, Random, RDatasets, DataFrames, PlotThemes
gr() #plotly() #pyplot() #plotlyjs() #pgfplotsx() #unicodeplots()
theme(:ggplot2)
Gráficas con Julia usando Plots
Cargamos los paquetes necesarios:
- Plots: para crear gráficos.
- StatsPlots: para gráficos estadísticos.
- Distributions: para trabajar con distribuciones de probabilidad.
- Random: para generar números aleatorios.
- RDatasets: para acceder a algunos de los conjuntos de datos de R.
- DataFrames: para manejar datos en formato de tabla.
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)
= 5 .*rand(20) .+ 10
x1 = rand(Normal(),200)
x2 = rand(Poisson(3),300)
x3 = rand(10,4); x4
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, π,
="Funciones seno y coseno",
title="Eje x",
xlabel="Eje y",
ylabel=:bottomleft,
legend=2,
legendcolumns=[(π/2, 0, text("sen(x)", :left, 12, :blue)),
annotationsπ/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,
="Histograma de x3",
title="x3",
xlabel="Frecuencia",
ylabel=:chartreuse,
color=0.6
alpha )
Histograma con áreas iguales
ea_histogram(x3,
="Histograma de x3 con áreas iguales",
title="x3",
xlabel="Frecuencia",
ylabel=:deepskyblue,
color=0.6) alpha
Diagrama circular
= ["Nerds", "Hackers", "Scientists"]
x = [0.4, 0.35, 0.25]
y pie(x, y, title = "The Julia Community", l = 0.5)
Superposición de gráficas
= randn(10^3)
x p(x) = 1/sqrt(2pi) * exp(-x^2/2)
= range(-5, 5, length=21)
b_rango
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))
= randn(20) .+ 2
datos 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)
)
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,
= :Gender,
group = "Height (cm)",
xlabel = "Weight (kg)",
ylabel = "Height vs Weight by Gender",
title = 6,
markersize = 0.7
alpha )
@df df histogram(:Age,
= 10,
bins = "Age",
xlabel = "Count",
ylabel = "Age Distribution",
title = :orange,
color = 0.6) alpha
@df df boxplot(:Gender, :Weight,
= :Gender,
group = "Gender",
xlabel = "Weight (kg)",
ylabel = "Weight Distribution by Gender",
title = [:blue :pink],
color = false
legend )
Gráfica de barras
= ["Cat", "Dog", "Bird", "Fish", "Dog", "Cat", "Dog", "Bird", "Cat", "Cat"]
animals
# Count frequencies
using StatsBase
= countmap(animals)
freqs
# Separate keys and values
= collect(keys(freqs))
categories = collect(values(freqs))
counts
# Bar plot
bar(categories, counts,
= "Frequency of Animals",
title = "Animal",
xlabel = "Count",
ylabel = false,
legend = 0.6,
bar_width = :skyblue) color
A partir de un DataFrame, variable cualitativa
= DataFrame(Animal = ["Cat", "Dog", "Bird", "Fish", "Dog", "Cat", "Dog", "Bird", "Cat", "Cat"])
df
# Count frequencies
= countmap(df.Animal)
freqs
# Convert to DataFrame for StatsPlots
= DataFrame(Animal = collect(keys(freqs)), Count = collect(values(freqs)))
freq_df
# Plot frequencies
@df freq_df bar(:Animal, :Count,
= "Frequency of Animals",
title = "Animal",
xlabel = "Count",
ylabel = false,
legend = 0.6,
bar_width = :green) color
A partir de un DataFrame variable discreta
using DataFrames, StatsBase, StatsPlots
# Example discrete numeric variable: dice rolls
= DataFrame(Roll = [1, 2, 3, 6, 2, 1, 4, 6, 6, 3, 2, 1, 5, 6, 4, 2])
df
# Count frequencies
= countmap(df.Roll)
freqs
# Convert to DataFrame
= DataFrame(Roll = collect(keys(freqs)), Count = collect(values(freqs)))
freq_df
# Bar plot
@df freq_df bar(:Roll, :Count,
= "Dice Roll Frequencies",
title = "Dice Value",
xlabel = "Count",
ylabel = false,
legend = 0.6,
bar_width = :purple) color
Recetas
= 1000
n = rand(Gamma(2), n)
x = -0.5x + randn(n)
y = marginalhist(x, y, fc = :plasma, bins = 40) plot1
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),
= "Dot Plot Example",
title = "X-axis",
xlabel = "Y-axis",
ylabel = (:circle, 8, :blue),
marker = false) legend
heatmap(rand(10,10),
= "Heatmap Example",
title = "X-axis",
xlabel = "Y-axis",
ylabel = :viridis,
color = true) legend
Animación
= @animate for t in 0:0.1:10
anim plot(sin.(0:0.1:2π) .+ 0.1t,
=(-2, 2),
ylim="Sine Wave Animation",
title=2,
lw=:blue)
colorend
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()
= @animate for t in 0:0.05:10
anim = [sin(3u + t) for u in 0:0.01:2π]
x = [sin(2u) for u in 0:0.01:2π]
y plot(x, y,
=(-1.2, 1.2), ylim=(-1.2, 1.2),
xlim=2, color=:red,
lw="Lissajous Curve Animation")
titleend
# 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
= @animate for θ in 0:5:360
anim = 0:0.1:10π
t = cos.(t)
x = sin.(t)
y = t/π
z plot(x, y, z,
= :path3d,
seriestype = 2,
lw = :blue,
color = (-1.5, 1.5),
xlim = (-1.5, 1.5),
ylim = (0, 11),
zlim = (θ, 30), # rotate camera
camera = "Rotating 3D Helix")
title 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