예제 #1
0
def plot_palette(doc, palette_name):
    # Create plots to compare the cmaps
    plot = doc.new(
        Plot(
            plot_path=filepath,
            plot_name=filename + '_' + palette_name,
            lines='3pt',
            height='6cm',
        ))
    cmap = PREDEFINED_CMAPS[palette_name]
    palette = PREDEFINED_PALETTES[palette_name]

    # Numer of colors shown in the plot
    n_colors = 25
    interp_param = np.linspace(0, 1, n_colors + 1)

    # Plot the hue(h)-lightness(J) space
    for i, JCh_color in zip(range(n_colors), palette):
        cmap.color_model = 'rgb'  # Default JCh color model takes the hue mod 360 to be a valid color, but this makes the color map look non-continuous. The rgb color model does not process any of the components.
        J1, C1, h1 = cmap(interp_param[i])
        J2, C2, h2 = cmap(interp_param[i + 1])
        cmap.color_model = 'JCh'  # Resetting the color model to the original

        plot.add_plot([h1, h2], [J1, J2], color=JCh_color, line_cap='round')

    plot.x_label = 'Hue angle $h$'
    plot.y_label = 'Lightness $J$'

    plot.caption = f'The \\texttt{{{palette_name}}} color map'

    # Show the generated colors in squares using TikZ.
    for n_colors in [2, 3, 4, 5, 6, 9]:
        doc += f'{n_colors} colors: \\hspace{{10pt}}'
        tikzpicture = doc.new(
            TexEnvironment('tikzpicture', options=['baseline=-.5ex']))
        for i, color in zip(range(n_colors), palette):
            tikzpicture += Node((i, 0), fill=color)
        doc += ' '
x = [1, 2, 3, 4]
y1 = [32, 43, 45, 61]
y2 = [45, 51, 43, 34]
labels = ['Dataset 1', 'Dataset 2', 'Dataset 3', 'Dataset 4']

plot = Plot(
    plot_path='./examples/',
    plot_name='bar_chart_example',
    as_float_env=False,
    marks=False,
    lines=False,
    grid='none',
    grid_style=('line width=.2pt', 'gray!50'),
    ymajorgrids='true',
    width='7cm',
    height='6cm',
    axis_line_style='{draw=none}',
    legend_cell_align='{left}',
    legend_style='{font=\\footnotesize, draw=none, fill=none}',
    ylabel_style='{yshift=-3.5mm}',
    bar_width='4mm',
    ybar='0mm',
    xticklabel_style='{font=\\footnotesize}',
    xtick_style='{draw=none}',
    ytick_style='{draw=none}',
)
plot.axis.options += (
    'nodes near coords',
    'every node near coord/.append style={font=\\scriptsize}',
)
예제 #3
0
from python2latex import Document, Plot
import numpy as np

# Document type 'standalone' will only show the plot, but does not support all tex environments.
filepath = './examples/simple plot example/'
filename = 'simple_plot_example'
doc = Document(filename, doc_type='standalone', filepath=filepath)

# Create the data
X = np.linspace(0,2*np.pi,100)
Y1 = np.sin(X)
Y2 = np.cos(X)

# Create a plot
plot = doc.new(Plot(X, Y1, X, Y2, plot_path=filepath, as_float_env=False))

tex = doc.build()
    ],  # Indigo
    color_model='JCh',
    color_transform=lambda c: tuple(JCh2rgb(c)))

cmap_def = r'\pgfplotsset{compat=1.14, colormap={bint}{' + '\n\t'.join(
    f'rgb({i})={cmap(i)}' for i in np.linspace(0, 1, 25)) + '}}'

plot = Plot(
    plot_path='./examples/',
    plot_name='heatmap_example',
    as_float_env=False,
    lines=False,
    grid=False,
    width='7.5cm',
    height='7.5cm',
    axis_line_style='{draw=none}',
    enlargelimits='false',
    y_dir='reverse',
    axis_x='top',
    x_tick_label_style='{font=\\footnotesize}',
    y_tick_label_style='{font=\\footnotesize}',
    colorbar_style=
    '{ylabel=Attention, ylabel style={rotate=180}, yticklabels={0.00,0.25,0.50,0.75,1.00}, ytick={0,0.25,0.5,0.75,1}}'
)

plot.add_matrix_plot(X, Y, Z)
for i, zz in enumerate(Z):
    for j, z in enumerate(zz):
        if z > .6:
            plot.axis += f'\\node[white] at ({i},{j}) {{\\scriptsize {z:.2f} }};'
예제 #5
0
filename = 'simple_matrix_plot_example'
doc = Document(filename,
               doc_type='standalone',
               filepath=filepath,
               border='1cm')

# Create the data
X = np.linspace(-3, 3, 11)
Y = np.linspace(-3, 3, 21)

# Create a plot
plot = doc.new(
    Plot(plot_name=filename,
         plot_path=filepath,
         as_float_env=False,
         grid=False,
         lines=False,
         enlargelimits='false',
         width=r'.5\textwidth',
         height=r'.5\textwidth'))

XX, YY = np.meshgrid(X, Y)
Z = np.exp(
    -(XX**2 + YY**2) / 6
).T  # Transpose is necessary because numpy puts the x dimension along columns and y dimension along rows, which is the opposite of a standard graph.
plot.add_matrix_plot(X, Y, Z)

# Adding titles and labels
plot.x_label = 'X axis'
plot.y_label = 'Y axis'
plot.title = 'Some title'
palette = Palette(colors=cmap, color_model='rgb')

pal = Palette(colors=cmap, n_colors=2)

# Create the data
X = np.linspace(-1, 1, 50)
Y = lambda c: np.exp(X * c) + c

# Let us compare the different color palettes generated for different number of line plots
for n_colors in [2, 3, 5, 10]:
    # Create a plot
    plot = doc.new(
        Plot(
            plot_name=filename + f'n_colors={n_colors}',
            plot_path=filepath,
            width='\\textwidth',
            height='.21\\paperheight',
            palette=palette,
        ))

    for c in np.linspace(.5, 1.5, n_colors):
        plot.add_plot(X, Y(c), label=f'\\footnotesize $c={c:.3f}$'
                      )  # Add labels (default is at end of line plot)

    plot.x_min = -1
    plot.x_max = 1.3

    doc += '\n'

tex = doc.build()
# Create the document
filepath = './examples/more complex plot example/'
filename = 'more_complex_plot_example'
doc = Document(filename, doc_type='article', filepath=filepath)
sec = doc.new_section('More complex plot')
sec.add_text(
    'This section shows how to make a more complex plot integrated directly into a tex file.'
)

# Create the data
X = np.linspace(0, 2 * np.pi, 100)
Y1 = np.sin(X)
Y2 = np.cos(X)

# Create a plot
plot = sec.new(Plot(plot_name=filename, plot_path=filepath))
plot.caption = 'More complex plot'

nice_blue = Color(.07, .22, .29, color_name='nice_blue')
nice_orange = Color(.85, .33, .28, color_name='nice_orange')

plot.add_plot(X, Y1, nice_blue, 'dashed',
              legend='sine')  # Add colors and legend to the plot
plot.add_plot(X, Y2, nice_orange, line_width='3pt', legend='cosine')
plot.legend_position = 'south east'  # Place the legend where you want

# Add a label to each axis
plot.x_label = 'Radians'
plot.y_label = 'Projection'

# Choose the limits of the axis
예제 #8
0
    def heatmap_all_to_latex(self, experiment, sec, mean_metrics, x_label,
                             y_label, caption, file_path, file_name):
        plot = sec.new(
            Plot(plot_name=file_name,
                 plot_path=file_path,
                 grid=False,
                 lines=False,
                 enlargelimits='false',
                 width=r'.42\textwidth',
                 height=r'.42\textwidth',
                 position='th!',
                 label=file_name,
                 name='plot0'))
        plot.caption = caption

        kwargs_per_plot = {
            1: {
                'as_float_env': False,
                'at': '(plot0.south east)',
                'anchor': 'south west',
                'xshift': r'.12\textwidth',
                'name': 'plot1'
            },
            2: {
                'as_float_env': False,
                'at': '(plot0.south west)',
                'anchor': 'north west',
                'yshift': r'-0.07\textwidth',
                'name': 'plot2'
            },
            3: {
                'as_float_env': False,
                'at': '(plot2.south east)',
                'anchor': 'south west',
                'xshift': r'.12\textwidth',
                'name': 'plot3'
            }
        }
        titles = {
            'de': 'English-Deutsch',
            'it': 'English-Italian',
            'fi': 'English-Finnish',
            'es': 'English-Spanish'
        }

        for i, language in enumerate(sorted(mean_metrics['accuracies'])):
            if i == 0:
                current_plot = plot
            else:
                current_plot = Plot(plot_name=file_name,
                                    plot_path=file_path,
                                    grid=False,
                                    lines=False,
                                    enlargelimits='false',
                                    width=r'.42\textwidth',
                                    height=r'.42\textwidth',
                                    position='th!',
                                    **kwargs_per_plot[i])
                current_plot.tikzpicture.head = ''
                current_plot.tikzpicture.tail = ''

            x_values, y_values = sorted(
                experiment.CHANGING_PARAMS[x_label]), sorted(
                    experiment.CHANGING_PARAMS[y_label])
            z = np.zeros((len(x_values), len(y_values)), dtype=float)

            for x_idx, x_value in enumerate(x_values):
                for y_idx, y_value in enumerate(y_values):
                    z[x_idx, y_idx] = float(
                        mean_metrics['accuracies'][language][(str(y_value),
                                                              str(x_value))])

            z = np.around(z, 2)

            if i >= 2:
                current_plot.x_label = r'$p_{factor}$'
                current_plot.x_ticks_labels = [
                    '{:.1f}'.format(x) for x in x_values
                ]
            else:
                current_plot.x_ticks_labels = [r'\empty']

            if i % 2 == 0:
                current_plot.y_label = r'$p_0$'
                current_plot.y_ticks_labels = [
                    '{:.2f}'.format(y) for y in y_values
                ]
            else:
                current_plot.y_ticks_labels = [r'\empty']

            x_values = list(range(len(x_values)))
            y_values = list(range(len(y_values)))

            current_plot.x_ticks = x_values
            current_plot.y_ticks = y_values

            delta = z.max() - z.min()
            point_min = z.min() - delta / 2
            point_max = z.max() + delta / 2

            current_plot.add_matrix_plot(x_values,
                                         y_values,
                                         z,
                                         point_meta_min=point_min,
                                         point_meta_max=point_max)
            current_plot.axis.options += (
                r'nodes near coords={\pgfmathprintnumber\pgfplotspointmeta}',
                r'every node near coord/.append style={xshift=0pt,yshift=-7pt, black, font=\footnotesize}',
            )

            current_plot.axis.kwoptions[
                'colorbar_style'] = '{{/pgf/number format/fixed zerofill, /pgf/number format/precision=1}}'

            current_plot.title = titles[language]
            current_plot.plot_name += '_en_{}'.format(language)

            if i > 0:
                plot.tikzpicture += current_plot
예제 #9
0
    def plot_all_to_latex(self, sec, mean_metrics, std_metrics, caption,
                          file_path, file_name):
        plot = sec.new(
            Plot(plot_name=file_name,
                 plot_path=file_path,
                 position='th!',
                 width=r'.27\textwidth',
                 height=r'.25\textwidth',
                 label=file_name,
                 name='plot0',
                 xshift=r'-.115\textwidth'))
        plot.caption = caption

        kwargs_per_plot = {
            1: {
                'as_float_env': False,
                'at': '(plot0.south east)',
                'anchor': 'south west',
                'xshift': r'-.04\textwidth',
                'name': 'plot1'
            },
            2: {
                'as_float_env': False,
                'at': '(plot1.south east)',
                'anchor': 'south west',
                'xshift': r'0.035\textwidth',
                'name': 'plot2'
            },
            3: {
                'as_float_env': False,
                'at': '(plot2.south east)',
                'anchor': 'south west',
                'xshift': r'.11\textwidth',
                'name': 'plot3'
            }
        }
        titles = {
            'de': 'English-Deutsch',
            'it': 'English-Italian',
            'fi': 'English-Finnish',
            'es': 'English-Spanish'
        }

        for i, language in enumerate(sorted(mean_metrics['accuracies'])):
            if i == 0:
                current_plot = plot
            else:
                current_plot = Plot(plot_name=file_name,
                                    plot_path=file_path,
                                    width=r'.27\textwidth',
                                    height=r'.25\textwidth',
                                    **kwargs_per_plot[i])
                current_plot.tikzpicture.head = ''
                current_plot.tikzpicture.tail = ''

            x, y, std = np.array(
                list(mean_metrics['accuracies'][language].keys())).astype(
                    int), np.array(
                        list(mean_metrics['accuracies']
                             [language].values())).astype(float), np.array(
                                 list(std_metrics['accuracies']
                                      [language].values())).astype(float)
            sorting = x.argsort()
            x, y, std = x[sorting], y[sorting], std[sorting]

            current_plot.add_plot(x,
                                  y,
                                  'blue',
                                  'ylabel near ticks',
                                  mark='*',
                                  line_width='1.2pt',
                                  mark_size='.9pt')
            current_plot.add_plot(x,
                                  y + 1.96 * std,
                                  name_path='upper',
                                  draw='none')
            current_plot.add_plot(x,
                                  y - 1.96 * std,
                                  name_path='lower',
                                  draw='none')
            current_plot.axis.append(
                '\\addplot[fill=blue!10] fill between[of=upper and lower];')
            current_plot.axis.kwoptions[
                'y tick label style'] = '{/pgf/number format/fixed zerofill, /pgf/number format/precision=1}'

            current_plot.x_min = np.floor(x.min())
            current_plot.x_max = np.ceil(x.max())
            y_max, y_min = (y + 1.96 * std).max(), (y - 1.96 * std).min()
            delta = y.max() - y.min()
            current_plot.y_min = y_min - delta / 2
            current_plot.y_max = y_max + delta / 2

            current_plot.title = titles[language]
            current_plot.plot_name += '_en_{}'.format(language)

            if i > 0:
                plot.tikzpicture += current_plot
def f(x, a=1, b=1.5, c=400, d=8):
    return np.clip((1 / (a * x)**4 - d / (a * x)**3) / c + b, -5, 6.3)


y1 = f(x)
y2 = f(x, .8, 2)
y3 = f(x, .65, 2.5)
y4 = f(x, .55, 3)
y5 = f(x, .5, 3.5)

plot = Plot(
    plot_path='./examples/',
    plot_name='lineplot_example',
    as_float_env=False,
    grid_style=('gray!35', 'ultra thin'),
    width='7cm',
    height='6cm',
    ylabel_style='{yshift=-3.5mm}',
)

plot.add_plot(x * 1000, y1, label='\\scriptsize$p=10$')
plot.add_plot(x * 1000, y2, label='\\scriptsize$p=30$')
plot.add_plot(x * 1000, y3, label='\\scriptsize$p=50$')
plot.add_plot(x * 1000, y4, label='\\scriptsize$p=75$')
plot.add_plot(x * 1000, y5, label='\\scriptsize$p=100$')

plot.y_min = 0
plot.y_max = 6.2
plot.x_min = 0
plot.x_max = 900
x1 = np.random.normal(1, 1.4, 20)
x1 -= min(x1) - .5
y1 = x1 + np.random.normal(0, .7, 20)

x2 = np.random.normal(6, 2, 15)
y2 = x2 + np.random.normal(0, .5, 15)


plot = Plot(
    plot_path='./examples/',
    plot_name='scatterplot',
    as_float_env=False,
    marks=True,
    lines=False,
    grid_style=('gray!35', 'ultra thin'),
    width='7cm',
    height='6cm',
    legend_cell_align='{left}',
    legend_style='{font=\\footnotesize,draw=gray!50}',
    ylabel_style='{yshift=-3.5mm}',
)

plot.add_plot(x1, y1+2, legend='Cercle indigo', fill_opacity=.5)
plot.add_plot(x2, y2+2, mark='triangle*', mark_size='2.5pt', legend='Triangle orange', fill_opacity=.5)

plot.legend_position = 'south east'

plot.y_min = 0
plot.x_min = 0
plot.x_ticks = (0,2,4,6,8)
예제 #12
0
# Adding necessary library to preamble for colormaps
doc.add_to_preamble(r'\usepgfplotslibrary{colorbrewer}')
doc.add_to_preamble(r'\pgfplotsset{compat=1.15, colormap/Blues-3}')

# Create the data
X = np.array([0.05, 0.1, 0.2])
Y = np.array([1.5, 2.0, 3.0, 4.0])
Z = np.random.random((3, 4))

# Create a plot
plot = sec.new(
    Plot(plot_name=filename,
         plot_path=filepath,
         grid=False,
         lines=False,
         enlargelimits='false',
         width=r'.6\textwidth',
         height=r'.8\textwidth'))
plot.caption = 'Matrix plot of some random numbers as probabilities'
plot.add_matrix_plot(
    range(len(X)), range(len(Y)), Z
)  # Dummy values for x and y so that the region are all the same size, even though the values of X and Y are not linear.

# Adding more complex custom options to the axis (see PGFPlots documentation)
plot.axis.options += (
    r'nodes near coords={\pgfmathprintnumber\pgfplotspointmeta\,\%}',
    r'every node near coord/.append style={xshift=0pt,yshift=-7pt, black, font=\footnotesize}',
)

# Add a label to each axis
예제 #13
0
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
data = [iris[feature] for feature in features]
# Using seaborn to produce the violin plots
ax = sns.violinplot(data=data, cut=2.3, gridsize=200, bw=.2)

plot = Plot(
    plot_path='./examples/',
    plot_name='violin_plot_example',
    as_float_env=False,
    grid='none',
    ymajorgrids='true',
    grid_style=('gray!35', 'ultra thin'),
    width='7cm',
    height='6cm',
    ylabel_style='{yshift=-4mm}',
    xlabel_style='{yshift=-3.5mm}',
    axis_line_style='{draw=none}',
    x_tick_label_style='{align=center, font=\\scriptsize}',
    xtick_style='{draw=none}',
    ytick_style='{draw=none}',
)

palette = holi(4)

for i, feature in enumerate(features):
    x, y = ax.collections[2 * i]._paths[
        0]._vertices.T  # Hacking into matplotlib objects to find the data defining the envelope

    q25, q50, q75 = np.percentile(data[i], [25, 50, 75])
from python2latex import Template, Table, Plot

filepath = './examples/templating an existing file'
template = Template(filename='already_existing_file', filepath=filepath)

table = Table((4, 3))
table[1:, 0:] = [[i for _ in range(3)] for i in range(3)]
table[0] = 'Title'
table[0].add_rule()
table.caption = 'Here is a table caption.'

template.anchors['some_table'] = table

plot = Plot(plot_name='some_plot', plot_path=filepath)
plot.add_plot(list(range(10)), list(range(10)), 'red')
plot.caption = 'Here is a figure caption.'

template.anchors['some_figure'] = plot

template.render()
    cmap_range=(0,1),
    n_colors=n_colors,
    color_transform=lambda color: (rgb2JCh(hsv_to_rgb(color))[0]/100,)
)
palette_hsb_gray = Palette(
    cmap_hsb,
    color_model='gray',
    cmap_range=(0,1),
    n_colors=n_colors,
    color_transform=lambda color: (rgb2gray(hsv_to_rgb(color)),)
)

# Create plots to compare the cmaps
plot_color = doc.new(Plot(plot_path=filepath,
                          plot_name=filename+'_color',
                          lines='3pt',
                          height='6cm',
                          ))
plot_lightness = doc.new(Plot(plot_path=filepath,
                              plot_name=filename+'_lightness',
                              lines='3pt',
                              height='6cm',
                              ))
plot_gray = doc.new(Plot(plot_path=filepath,
                         plot_name=filename+'_gray',
                         lines='3pt',
                         height='6cm',
                         ))

def unfold_hue(h):
    """Adds 360 degrees of hue when the hue value is less than the starting value to make sure the plots are continuous."""