Why are the simple things so non-intuitive?
Image by halfrain — source and license.
I love Mathematica notebooks, for analytical calculations, prototyping algorithms, and most of all: plotting and analyzing data.
Importing and plotting some data is easy enough:
SetDirectory[NotebookDirectory[]];
data = Import["my_data_file.txt", "Table"];
ListLinePlot[data]
But setting the options right on those plots is so confusing. What are the default colors? How do you adjust the font sizes? The legend? The legend sizes? Color functions? Exporting the plot with correct resolution? Getting the layout of the plots to come out right? Scaling multiple plot ranges?
Let’s get into it.
I use the “scientific” plot theme in Mathematica. Often, I want to manually set the colors in a plot. But how do you get those colors? The confusing command to get them is:
colors = (("DefaultPlotStyle" /. (Method /.
Charting`ResolvePlotTheme["Scientific", ListLinePlot])) /.
Directive[x_, __] :> x);
Mathematica scientific theme colors.
Even crazier: if you don’t use the “scientific” theme, the default colors are:
colors = Table[ColorData[97][i], {i, 1, 15}]
Default colors in Mathematica.
I mean, seriously? ColorData[97]
is the default?
The default font sizes in plots are way too small:
plt = Plot[{Sin[x], Cos[x]}, {x, 0, 2*Pi}, PlotLabel -> "Plots"]
Default font size
It’s possible to set individual sizes for each axis and the label, but it’s easier to use BaseStyle
to adjust it everywhere:
plt = Plot[{Sin[x], Cos[x]}, {x, 0, 2*Pi}, PlotLabel -> "Plots", BaseStyle -> {FontSize -> 24}]
Human readable font size.
Let’s see how a plot legend looks.
colors = (("DefaultPlotStyle" /. (Method /.
Charting`ResolvePlotTheme["Scientific", ListLinePlot])) /.
Directive[x_, __] :> x);
leg = LineLegend[colors[[;; 2]], {"Sin", "Cos"}];
p1 = Plot[{Sin[x], Cos[x]}, {x, 0, 2*Pi}, PlotLegends -> leg]
Tiny legend.
To set the legend size for the font, we need to use the very confusing: LabelStyle -> Directive[FontSize -> 24]
. To make the lines next to the text larger, we can use: LegendMarkerSize -> 40
.
colors = (("DefaultPlotStyle" /. (Method /.
Charting`ResolvePlotTheme["Scientific", ListLinePlot])) /.
Directive[x_, __] :> x);
leg = LineLegend[colors[[;; 2]], {"Sin", "Cos"},
LabelStyle -> Directive[FontSize -> 24], LegendMarkerSize -> 40];
p2 = Plot[{Sin[x], Cos[x]}, {x, 0, 2*Pi}, PlotLegends -> leg,
ImageSize -> 400]
Legends for humans.
#coding #programming #data-science #visualization #visual studio code