Why are the simple things so non-intuitive?

Image for post

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.


1. What are the default colors?

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);

Image for post

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}]

Image for post

Default colors in Mathematica.

I mean, seriously? ColorData[97] is the default?

2. Base style in plots

The default font sizes in plots are way too small:

plt = Plot[{Sin[x], Cos[x]}, {x, 0, 2*Pi}, PlotLabel -> "Plots"]

Image for post

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}]

Image for post

Human readable font size.

3. Color functions and scaling

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]

Image for post

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]

Image for post

Legends for humans.

#coding #programming #data-science #visualization #visual studio code

7 tricks for beautiful plots with Mathematica
9.15 GEEK