Coder Social home page Coder Social logo

garrettj403 / scienceplots Goto Github PK

View Code? Open in Web Editor NEW
6.5K 59.0 673.0 85.37 MB

Matplotlib styles for scientific plotting

License: MIT License

Python 100.00%
matplotlib-style-sheets matplotlib-figures scientific-papers thesis-template matplotlib-styles python cjk-fonts ieee-paper latex

scienceplots's Introduction

Hi there ๐Ÿ‘‹

Here are some of my software projects:

  • Related to RF engineering:
    • DispersionTransform: map dispersive waveguide data from the frequency- to distance-domain
    • CZT: calculate the Chirp Z-Transform, a flexible implementation of the Fast Fourier Transform
    • GradientModel: calculate the effective conductivity of a rough metallic surface using the Gradient Model
    • Mattis-Bardeen: calculate the surface impedance of a superconductor using Mattis-Bardeen theory
    • Waveguide: calculate the various properties of rectangular waveguides, e.g., phase constant, conductor loss, etc.
    • RF-tools: various tools for RF engineering, including useful command line tools
  • Related to radio astronomy:
    • QMix: simulate quantum tunnneling in SIS junctions
  • Other projects:
    • SciencePlots: format your Python/Matplotlib plots for scientific papers, theses and presentations

scienceplots's People

Contributors

cjwcommuny avatar echedey-ls avatar garrettj403 avatar gobinathj avatar hsins avatar jborrow avatar jobayer avatar mishagrol avatar splines avatar surajiyer avatar timcera avatar whitesymmetry avatar yuriok avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scienceplots's Issues

IEEE cycler limit

Hi! Just discovered this repo and love how helpful it is.

I've noticed the IEEE style has a detail that is annoying me. The default plot styles are this ones:
ieee-default

So it only allows up to 4 different plot styles. I've tried to change the cycles order using

from cycler import cycler
plt.rcParams.update({"axes.prop_cycle": cycler('linestyle', ['-', '--', ':', '-.'])*cycler('color', ['k', 'r', 'b', 'g'])})

to get the linestyles to iterate over the colors, creating up to 16 new ploting styles.
ieee-new-cycler

Maybe you want to change it in the repo.

Thanks for sharing your work!

Latex Option Clash when Saving Figure

Trying to save a figure using the savefig routine throws the following latex compilation error on my machine with MacTeX-2018 installed:

! LaTeX Error: Option clash for package graphicx.

Here is a minimal example that produces the failure.

import matplotlib as plt

with plt.style.context('science'):
    plt.plot([1, 2, 3, 4], [1, 2, 3, 4])
    plt.savefig('figure.eps', format='eps')

The compilation and subsequent saving work fine if the pgfplots packages is removed from the preamble directive in science.mplstyle.
I'm not sure how this change affects the figures.

text.latex.preamble : \usepackage{amsmath}, \usepackage[T1]{fontenc}

How to keep the same color for two or more plots

Hello,
Thank you for this repo, it is amazing.
I have a question regarding the styles, say I use the ieee style to draw the graphs:

plt.style.use(['ieee', 'no-latex'])
plt.plot(x1,y1)
plt.plot(x2, y2)
plt.plot(x3, y3)

I will get the plots with three different line styles. How can I force for example y1 and y2 to be drawn with the same line style but y3 by another?
I could manually, add a linestyle attribute for each plot, but is there a way to use the previous style?

Thanks

Use SciencePlots in Google Colab

I was trying to get this to work in Google Colab for some hours until I found the solution.
Unlike the desktop you have to reload the style libraries to recognize and use the new *.mplstyle files.

!pip install SciencePlots
import matplotlib.pyplot as plt
plt.style.reload_library() # <<<<<<<<<<
plt.style.use(['science', 'no-latex'])

Maybe you can add this in the README under Installation if someone else wants to use SciencePlots in Google Colab and encounters the problem.
Thanks! Great library!

Creating grids and grey background on google colab

Hey.

I was using your package to create graphs for master thesis and has encountered some issues.

The figures doesn't seem to be created with the same layout as shown on the readme and in the examples.

I have imported the library and used the reload command.

I have used the following script to create a duplicate of the examples:

`def model(x, p):
return x ** (2 * p + 1) / (1 + x ** (2 * p))

pparam = dict(xlabel='Voltage (mV)', ylabel='Current ($\mu$A)')

x = np.linspace(0.75, 1.25, 201)

with plt.style.context(['science']):
fig, ax = plt.subplots()
for p in [10, 15, 20, 30, 50, 100]:
ax.plot(x, model(x, p), label=p)
ax.legend(title='Order')
ax.autoscale(tight=True)
ax.set(**pparam)
fig.savefig('fig1.jpeg',dpi=300)`

fig1

RuntimeError: LaTeX was not able to process the following string

Trying to reproduce the example:

import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use(['science','ieee'])

x = np.linspace(0.75, 1.25, 201)

def model(x, p):
    return x ** (2 * p + 1) / (1 + x ** (2 * p))

fig, ax = plt.subplots()
for p in [10, 15, 20, 30, 50, 100]:
    ax.plot(x, model(x, p), label=p)
ax.legend(title=r'Order')
ax.set(xlabel=r'$V_0 / V_\mathrm{{gap}}$')
ax.set(ylabel=r'$I_\mathrm{{dc}}^0 / I_\mathrm{{gap}}$')
ax.autoscale(tight=True)
plt.show()


RuntimeError                              Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
    330                 pass
    331             else:
--> 332                 return printer(obj)
    333             # Finally look for special method names
    334             method = get_real_method(obj, self.print_method)

~/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
    235 
    236     if 'png' in formats:
--> 237         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    238     if 'retina' in formats or 'png2x' in formats:
    239         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    119 
    120     bytes_io = BytesIO()
--> 121     fig.canvas.print_figure(bytes_io, **kw)
    122     data = bytes_io.getvalue()
    123     if fmt == 'svg':

~/anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2198                     orientation=orientation,
   2199                     dryrun=True,
-> 2200                     **kwargs)
   2201                 renderer = self.figure._cachedRenderer
   2202                 bbox_inches = self.figure.get_tightbbox(renderer)

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    543 
    544     def print_png(self, filename_or_obj, *args, **kwargs):
--> 545         FigureCanvasAgg.draw(self)
    546         renderer = self.get_renderer()
    547         original_dpi = renderer.dpi

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    462 
    463         try:
--> 464             self.figure.draw(self.renderer)
    465         finally:
    466             RendererAgg.lock.release()

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65 

~/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer)
   1142 
   1143             mimage._draw_list_compositing_images(
-> 1144                 renderer, self, dsu, self.suppressComposite)
   1145 
   1146             renderer.close_group('figure')

~/anaconda3/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
    137     if not_composite or not has_images:
    138         for zorder, a in dsu:
--> 139             a.draw(renderer)
    140     else:
    141         # Composite any adjacent images together

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65 

~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2424             renderer.stop_rasterizing()
   2425 
-> 2426         mimage._draw_list_compositing_images(renderer, self, dsu)
   2427 
   2428         renderer.close_group('axes')

~/anaconda3/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
    137     if not_composite or not has_images:
    138         for zorder, a in dsu:
--> 139             a.draw(renderer)
    140     else:
    141         # Composite any adjacent images together

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65 

~/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1136         ticks_to_draw = self._update_ticks(renderer)
   1137         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
-> 1138                                                                 renderer)
   1139 
   1140         for tick in ticks_to_draw:

~/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py in _get_tick_bboxes(self, ticks, renderer)
   1076         for tick in ticks:
   1077             if tick.label1On and tick.label1.get_visible():
-> 1078                 extent = tick.label1.get_window_extent(renderer)
   1079                 ticklabelBoxes.append(extent)
   1080             if tick.label2On and tick.label2.get_visible():

~/anaconda3/lib/python3.6/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
    965             raise RuntimeError('Cannot get window extent w/o renderer')
    966 
--> 967         bbox, info, descent = self._get_layout(self._renderer)
    968         x, y = self.get_unitless_position()
    969         x, y = self.get_transform().transform_point((x, y))

~/anaconda3/lib/python3.6/site-packages/matplotlib/text.py in _get_layout(self, renderer)
    351         tmp, lp_h, lp_bl = renderer.get_text_width_height_descent('lp',
    352                                                          self._fontproperties,
--> 353                                                          ismath=False)
    354         offsety = (lp_h - lp_bl) * self._linespacing
    355 

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    228             fontsize = prop.get_size_in_points()
    229             w, h, d = texmanager.get_text_width_height_descent(s, fontsize,
--> 230                                                                renderer=self)
    231             return w, h, d
    232 

~/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    674         else:
    675             # use dviread. It sometimes returns a wrong descent.
--> 676             dvifile = self.make_dvi(tex, fontsize)
    677             dvi = dviread.Dvi(dvifile, 72 * dpi_fraction)
    678             try:

~/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py in make_dvi(self, tex, fontsize)
    421                      'string:\n%s\nHere is the full report generated by '
    422                      'LaTeX: \n\n' % repr(tex.encode('unicode_escape')) +
--> 423                      report))
    424             else:
    425                 mpl.verbose.report(report, 'debug')

RuntimeError: LaTeX was not able to process the following string:
b'lp'
Here is the full report generated by LaTeX: 



<matplotlib.figure.Figure at 0x7fbdfc553a20>```

fig_width problem

I found that I couldn't control the width of the figure. Did I do something wrong?

code

import numpy as np
import matplotlib.pyplot as plt


def function(x, p):
    return x ** (2 * p + 1) / (1 + x ** (2 * p))


pparam = dict(xlabel='Voltage (mV)', ylabel='Current ($\mu$A)')

x = np.linspace(0.75, 1.25, 201)

with plt.style.context(['science']):
    fig_width = 24 / 2.54  # 24cm
    fig_height = 6 / 2.54  # 6cm
    fig, ax = plt.subplots(figsize=(fig_width, fig_height))
    for p in [10, 15, 20, 30, 50, 100]:
        ax.plot(x, function(x, p), label=p)
    ax.legend(title='Order')
    ax.autoscale(tight=True)
    ax.set(**pparam)
    fig.savefig('fig1.pdf')
    fig.savefig('fig1.jpg', dpi=300)

result

ๅฎฝๅบฆไธๅฏน

The width of figure is not 24cm, but 20.09cm.

"Science" style not found on Google Colab

Hey there!

Thanks for the amazing project! Really useful for upcoming submissions ๐Ÿ˜…

Though, I ran into an issue when trying it out on Google Colab. I pip installed the style library following the instructions on the README. I then wrote down

import matplotlib.pyplot as plt

plt.style.use(['science','ieee'])

and it gave me the following error:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/matplotlib/style/core.py in use(style)
    113             try:
--> 114                 rc = rc_params_from_file(style, use_default_template=False)
    115                 _apply_style(rc)

5 frames
FileNotFoundError: [Errno 2] No such file or directory: 'science'

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/matplotlib/style/core.py in use(style)
    118                     "{!r} not found in the style library and input is not a "
    119                     "valid URL or path; see `style.available` for list of "
--> 120                     "available styles".format(style))
    121 
    122 

OSError: 'science' not found in the style library and input is not a valid URL or path; see `style.available` for list of available styles

Any remedies for this would be awesome!

Thanks :)

findfont: Font family ['serif'] not found. Falling back to DejaVu Sans.

os: win10
SciencePlots v1.0.9
matplotlib 3.3.0
python 3.8

I have put the NotoSerifSC fonts into "..\site-packages\matplotlib\mpl-data\fonts\ttf" and also try the following command:
import matplotlib.font_manager as fm fm._rebuild()

but still report "findfont: Font family ['serif'] not found. Falling back to DejaVu Sans.".

Manual installation

In "Installing SciencePlots manually", it seems to me that the command

cp styles/*/*.mplstyle ~/.matplotlib/stylelib/

is not sufficient because it doesn't copy the style-files that aren't in a directory and that are saved directy in "styles/". Which makes compilation fails because files are missing (science.mplstyle).

It seems to me that you have to add the command
cp styles/*/*.mplstyle ~/.matplotlib/stylelib/ && cp *.mplstyle ~/.matplotlib/stylelib/

Why not Times New Roman font?

Hi, I see many figures use Times New Roman font as default. Why don't you use it? If I want, how could I change the code? Thank you!

Styles not found in the style library

If you're using IPython and import matplotlib before installing SciencePlots, the style library won't be reloaded and therefore the styles won't be found.
Without restarting the kernel you can run

matplotlib.style.reload_library()

Maybe you could add this to setup script if running on IPython?

Underline in title string causes an error: RuntimeError: latex was not able to process the following string: b'giant_panda'

code here:

def draw_images_grid_with_labels(data, nrows, figsize=(12, 12), **subplots_adjust_param):
    import matplotlib.pyplot as plt

#     fig, axes = plt.subplots(nrows, len(data) // nrows)
#     for idx, item in enumerate(data):
#         i = idx % nrows # Get subplot row
#         j = idx // nrows # Get subplot column
# #         print(data[idx][0][0].shape)
#         img = data[idx][0][0].permute(1, 2, 0)
#         label = data[idx][1]
#         axes[i, j].imshow(img)
#         axes[i, j].set_title(label)
#     plt.subplots_adjust(wspace=0, hspace=0)
# #     plt.tight_layout()
#     plt.show()

    _, axes = plt.subplots(nrows, len(data) // nrows, figsize=figsize)
    axes = axes.flatten()
    for idx, (img, axe) in enumerate(zip(data, axes)):
        img = data[idx][0][0].permute(1, 2, 0)
        label = data[idx][1]
        axe.imshow(img)
        axe.set_title(label) # "_" will cause an error
#         axe.set_title(label.replace("_", ""))
        
    plt.subplots_adjust(**subplots_adjust_param)
#     plt.subplot_tool()
    plt.show()


params = {
    "left": 0.125,  # the left side of the subplots of the figure
    "right": 0.9,   # the right side of the subplots of the figure
    "bottom": 0,  # the bottom of the subplots of the figure
    "top": 0.3,     # the top of the subplots of the figure
    "wspace": 0.3,  # the amount of width reserved for space between subplots,
                  # expressed as a fraction of the average axis width
    "hspace": 0.3,  # the amount of height reserved for space between subplots,
                  # expressed as a fraction of the average axis height
}
import matplotlib
matplotlib.rcParams['axes.unicode_minus'] = False
with plt.style.context(['science']):
    draw_images_grid_with_labels(res, 2, **params)

error:

RuntimeError: latex was not able to process the following string:
b'giant_panda'

Here is the full report generated by latex:
This is pdfTeX, Version 3.141592653-2.6-1.40.22 (MiKTeX 21.3)
entering extended mode
(C:/Users/13567/.matplotlib/tex.cache/aac283e5eb249b2105d6afad043f1c69.tex
LaTeX2e <2020-10-01> patch level 4
L3 programming layer <2021-02-18> (D:\app\MiKTeX\tex/latex/base\article.cls
Document Class: article 2020/04/10 v1.4m Standard LaTeX document class
(D:\app\MiKTeX\tex/latex/base\size10.clo))
(D:\app\MiKTeX\tex/latex/type1cm\type1cm.sty)
(D:\app\MiKTeX\tex/latex/psnfss\mathptmx.sty)
(D:\app\MiKTeX\tex/latex/cm-super\type1ec.sty
(D:\app\MiKTeX\tex/latex/base\t1cmr.fd))
(D:\app\MiKTeX\tex/latex/base\inputenc.sty)
(D:\app\MiKTeX\tex/latex/geometry\geometry.sty
(D:\app\MiKTeX\tex/latex/graphics\keyval.sty)
(D:\app\MiKTeX\tex/generic/iftex\ifvtex.sty
(D:\app\MiKTeX\tex/generic/iftex\iftex.sty))
(D:\app\MiKTeX\tex/latex/geometry\geometry.cfg)

Package geometry Warning: Over-specification in `h'-direction.
    `width' (5058.9pt) is ignored.


Package geometry Warning: Over-specification in `v'-direction.
    `height' (5058.9pt) is ignored.

) (D:\app\MiKTeX\tex/latex/amsmath\amsmath.sty
For additional information on amsmath, use the `?' option.
(D:\app\MiKTeX\tex/latex/amsmath\amstext.sty
(D:\app\MiKTeX\tex/latex/amsmath\amsgen.sty))
(D:\app\MiKTeX\tex/latex/amsmath\amsbsy.sty)
(D:\app\MiKTeX\tex/latex/amsmath\amsopn.sty))
(D:\app\MiKTeX\tex/latex/base\textcomp.sty)
(D:\app\MiKTeX\tex/latex/psnfss\ot1ptm.fd)
(D:\app\MiKTeX\tex/latex/l3backend\l3backend-dvips.def)
(aac283e5eb249b2105d6afad043f1c69.aux)
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Missing $ inserted.
<inserted text> 
                $
l.19 {\rmfamily giant_
                      panda}
No pages of output.
Transcript written on aac283e5eb249b2105d6afad043f1c69.log.

Figure size for IEEE not setting correctly

I have been using this library to make some plots for use in IEEE papers.

When using plt.style.use(['science','ieee']) and fig.savefig('Figures/tradeproportion_orders.pdf') I find that the output is larger than a single IEEE column width.

Do you know why this is/ how to fix it?

x-axis order problem

Hi,
thanks for your work.
My x-axis is [100, 90, ..., 20, 10],
but when I run the following code

x-axis=[ i for i in reversed(range(10,101,10))]
with plt.style.context(['science']):
    fig,ax=plt.subplots()
    ax.plot(x-axis,y-axis)

the x-axis your figure showed me is [10, 20, ..., 90, 100].
How can i solve this problem?
wait for your repeat :)

Resolution of density scatter plots

Is there an option to keep the original scatter resolution obtainable without setting the plt style to 'science'?

Plot without science style disabled, high resolution in the scatter density plot
-Plot without science style disabled, high resolution in the scatter density plot
Same plot with science style enabled, notice low resolution in scatter density plot, especialy visible in top left corner region.
-Same plot with science style enabled, notice low resolution in scatter density plot, especialy visible in top left corner region.

Options Used for plotting:
plt.style.use(['science','ieee', 'scatter'])

science + grid not working

Hi,

Great package, I am using this for my master thesis. It's just fantastic to use. Just a small problem however -
plt.style.use(['science','grid']) seems not to work for me. Any suggestions on how to get it working?

Error because of comma between LaTeX package definitions

I get the following error if the comma is present in the marked line, if I remove the comma, it seems to work properly. The temporary files in the matplotlib cache directory also differ. Instead of $1.0$ the combination lp appears. Strange.

text.latex.preamble : \usepackage{amsmath}, \usepackage[T1]{fontenc}

With comma:

\documentclass{article}
\usepackage{type1cm}
\usepackage{textcomp}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}, \usepackage[T1]{fontenc}
\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
\pagestyle{empty}
\begin{document}
\fontsize{10.000000}{12.500000}{\rmfamily lp}
\end{document}

Without comma:

\documentclass{article}
\usepackage{type1cm}
\usepackage{textcomp}
\usepackage[utf8]{inputenc}
\usepackage{amsmath} \usepackage[T1]{fontenc}
\usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
\pagestyle{empty}
\begin{document}
\fontsize{10.000000}{12.500000}{\rmfamily $1.0$}
\end{document}
sys.platform # 'win32'
sys.version #'3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]'
mpl.__version__#'3.1.0'
plt.style.use("science")
xx = np.linspace(0, 2*np.pi, 1000)    
yy = np.sin(xx)
plt.plot(xx,yy)
[<matplotlib.lines.Line2D at 0x1f150e89988>]

Traceback (most recent call last):
  File "$anon_dir$\lib\site-packages\matplotlib\texmanager.py", line 304, in _run_checked_subprocess
    stderr=subprocess.STDOUT)
  File "$anon_dir$\lib\subprocess.py", line 395, in check_output
    **kwargs).stdout
  File "$anon_dir$\lib\subprocess.py", line 487, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['latex', '-interaction=nonstopmode', '--halt-on-error', 'C:\\Users\\username\\.matplotlib\\tex.cache\\f257b68706cc7f7375bc4f24a206f94f.tex']' returned non-zero exit status 1.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "$anon_dir$\lib\site-packages\matplotlib\backends\backend_qt5.py", line 501, in _draw_idle
    self.draw()
  File "$anon_dir$\lib\site-packages\matplotlib\backends\backend_agg.py", line 388, in draw
    self.figure.draw(self.renderer)
  File "$anon_dir$\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "$anon_dir$\lib\site-packages\matplotlib\figure.py", line 1709, in draw
    renderer, self, artists, self.suppressComposite)
  File "$anon_dir$\lib\site-packages\matplotlib\image.py", line 135, in _draw_list_compositing_images
    a.draw(renderer)
  File "$anon_dir$\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "$anon_dir$\lib\site-packages\matplotlib\axes\_base.py", line 2645, in draw
    mimage._draw_list_compositing_images(renderer, self, artists)
  File "$anon_dir$\lib\site-packages\matplotlib\image.py", line 135, in _draw_list_compositing_images
    a.draw(renderer)
  File "$anon_dir$\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "$anon_dir$\lib\site-packages\matplotlib\axis.py", line 1206, in draw
    renderer)
  File "$anon_dir$\lib\site-packages\matplotlib\axis.py", line 1151, in _get_tick_bboxes
    for tick in ticks if tick.label1.get_visible()],
  File "$anon_dir$\lib\site-packages\matplotlib\axis.py", line 1151, in <listcomp>
    for tick in ticks if tick.label1.get_visible()],
  File "$anon_dir$\lib\site-packages\matplotlib\text.py", line 890, in get_window_extent
    bbox, info, descent = self._get_layout(self._renderer)
  File "$anon_dir$\lib\site-packages\matplotlib\text.py", line 291, in _get_layout
    ismath="TeX" if self.get_usetex() else False)
  File "$anon_dir$\lib\site-packages\matplotlib\backends\backend_agg.py", line 201, in get_text_width_height_descent
    s, fontsize, renderer=self)
  File "$anon_dir$\lib\site-packages\matplotlib\texmanager.py", line 448, in get_text_width_height_descent
    dvifile = self.make_dvi(tex, fontsize)
  File "$anon_dir$\lib\site-packages\matplotlib\texmanager.py", line 338, in make_dvi
    texfile], tex)
  File "$anon_dir$\lib\site-packages\matplotlib\texmanager.py", line 317, in _run_checked_subprocess
    exc=exc.output.decode('utf-8'))) from exc
RuntimeError: latex was not able to process the following string:
b'lp'

Here is the full report generated by latex:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (MiKTeX 2.9.6500 64-bit)
entering extended mode
(C:/Users/username/.matplotlib/tex.cache/f257b68706cc7f7375bc4f24a206f94f.tex
LaTeX2e <2017-04-15>
Babel <3.15> and hyphenation patterns for 75 language(s) loaded.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files\MiKTeX 2.9\tex\latex\base\size10.clo"))
(C:\Users\username\AppData\Roaming\MiKTeX\2.9\tex\latex\type1cm\type1cm.sty)
("C:\Program Files\MiKTeX 2.9\tex\latex\base\textcomp.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\base\ts1enc.def"))
("C:\Program Files\MiKTeX 2.9\tex\latex\base\inputenc.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\base\utf8.def"
("C:\Program Files\MiKTeX 2.9\tex\latex\base\t1enc.dfu")
("C:\Program Files\MiKTeX 2.9\tex\latex\base\ot1enc.dfu")
("C:\Program Files\MiKTeX 2.9\tex\latex\base\omsenc.dfu")
("C:\Program Files\MiKTeX 2.9\tex\latex\base\ts1enc.dfu")))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsmath.sty"
For additional information on amsmath, use the `?' option.
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amstext.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsgen.sty"))
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsbsy.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\amsmath\amsopn.sty"))

! LaTeX Error: Missing \begin{document}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.10 \usepackage{amsmath},
                           \usepackage[T1]{fontenc}
No pages of output.
Transcript written on f257b68706cc7f7375bc4f24a206f94f.log.

Installation behind proxy not working.

I am trying to install SciencePlots behind a proxy using pip.
pip install SciencePlots --proxy http://proxy-ip:port
While the package download is working correctly, I encountered the following Error during the installation procedure:

Running command pip subprocess to install build dependencies
Using pip 22.0.3 from C:\Users\Username\AppData\Local\Temp\pip-standalone-pip-_nduq2qr\__env_pip__.zip\pip (python 3.9)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000002902A131340>, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/setuptools/

To me it seems like the proxy is somehow not consequently used. Is there a way to fix this?

[compatibility]Install from pypi broken down in python 3.9

When I installed SciencePlots from pypi, pip would throw out this error:

ModuleNotFoundError: No module named '_ctypes'.

And after installing SciencePlots, matplotlib would throw out this error:

OSError: 'ieee' not found in the style library and input is not a valid URL or path

Disabling (or adjusting) border ticks

Hey,

first of: thanks for the great styles!
I would however like to disable (or adjust if possible) the ticks the style draws on the borders of a plot. Specifically, when I'm building a subplot figure with a big figure around it to easily have a shared x, and y label, as well as legend, then the border ticks of the invisible frame stay visible.
The following code should showcase the problem:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

plt.style.use("science")
fig, axes = plt.subplots(5,2, figsize=(8,6), sharex=True, sharey=True)
axes = axes.flatten()
big = fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)

for ax in axes:
    ax.hist(
        np.random.normal(size=10000) + np.random.randint(0,10),
        density=True,
        bins=200,
    )

plt.show()

Note how the ticks are even plotted between two subplots in the whitespace. If you know how to selectively disable this, it would be appreciated.

Best regards,
Michael

How to solve this problem?

I can correctly run "plt.style.use('science')", but then, when I plot something, some error went out๏ผš"RuntimeError: Failed to process string with tex because latex could not be found"
how can I fix it? thanks!

Adding LaTeX packages for additional symbols to avoid process error

Hi.

This issue is already solved for me, but I wanted to share if somebody else comes across with it. I had a problem with symbols \circlearrowright & \circlearrowleft that I am using in a label. LaTeX was not able to process the string. Turns out that this symbols are under \usepackage{ amssymb }. So I needed to add this package to *.mplstyle under the folder "user.matplotlib\stylelib" as;

text.latex.preamble : \usepackage{amsmath} \usepackage{ amssymb }

Best,
Altug

A Couple Styles and pointer to complementary repo

Hi John,

I like your library! I have attached a couple style files for your to include in it.

Additionally, I have just published to Pypi, a complementary package for sizing publication figures and formatting panel labels (https://pypi.org/project/matplotlib-publishutil). It needs more layout config files for different publications, so as you develop style files, if you can provide my repo corresponding layout files, that'd be great!

Here is a Nature style (nature.mplstyle):

# Matplotlib style for Nature journal figures.
# In general, they advocate for all fonts to be panel labels to be sans serif
# and all font sizes in a figure to be 7 pt, and panel labels to be 8 pt. bold.

# Font sizes
axes.labelsize: 7
xtick.labelsize: 7
ytick.labelsize: 7
legend.fontsize: 7
font.size: 7

# Font Family
font.family: sans-serif
font.sans-serif: DejaVu Sans, Arial, Helvetica, Lucida Grande, Verdana, Geneva, Lucid, Avant Garde, sans-serif
mathtext.fontset : dejavusans

# Set line widths# 
axes.linewidth : 0.5
grid.linewidth : 0.5
lines.linewidth : 1.
lines.markersize: 3

# Always save as 'tight'
savefig.bbox : tight
savefig.pad_inches : 0.01  # Use virtually all space when we specify figure dimensions.

And here is a generic style file for when LaTeX is True and using a sans-serif font (latexsans.mplstyle).

mathtext.fontset : dejavusans

# Use LaTeX for math formatting
text.usetex : True
# In general, we need to be careful with the preamble. A common font for
# sans serif LaTeX is cmbright. However, it does not support bold fontweights
# so we use sfmath instead. 
text.latex.preamble : \usepackage{amsmath, amssymb, sfmath}

Axis ticks are shown abnormally when using 3d scatter plot

Hi, I met a problem when I use SciencePlot in 3d scatter plot. The axis ticks are shown abnormally. Below is an example that would reproduce the bug:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# Fixing random state for reproducibility
np.random.seed(19680801)
def randrange(n, vmin, vmax):
    '''
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin

with plt.style.context(["science", 'ieee', 'no-latex']):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    n = 100

    # For each set of style and range settings, plot n random points in the box
    # defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
    for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
        xs = randrange(n, 23, 32)
        ys = randrange(n, 0, 100)
        zs = randrange(n, zlow, zhigh)
        ax.scatter(xs, ys, zs, marker=m)

    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')

    plt.show()

This would produce the following figure. As you can see, the lower-right corner is strange and only half of the x and y labels are shown.
Example

pound sign '#' issue with Tex

Had some problems when I put a '#' in my subplot title.

latex was not able to process the following string:
b'HR Response Animal #2'

Here is the full report generated by latex:
This is pdfTeX, Version 3.141592653-2.6-1.40.23 (MiKTeX 21.8)
entering extended mode
(C:/Users/steph/.matplotlib/tex.cache/c6461476dd8de54b1e07f6b0e45f144a.tex
LaTeX2e <2021-06-01> patch level 1
L3 programming layer <2021-08-27>
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/base\article.cls
Document Class: article 2021/02/12 v1.4n Standard LaTeX document class
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/base\size10.clo))
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/type1cm\type1cm.sty)
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/psnfss\helvet.sty
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/graphics\keyval.sty))
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/base\textcomp.sty)
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/base\inputenc.sty)
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/amsmath\amsmath.sty
For additional information on amsmath, use the `?' option.
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/amsmath\amstext.sty
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/amsmath\amsgen.sty))
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/amsmath\amsbsy.sty)
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/amsmath\amsopn.sty))
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/amsfonts\amssymb.sty
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/amsfonts\amsfonts.sty))
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/sfmath\sfmath.sty)
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/geometry\geometry.sty
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/generic/iftex\ifvtex.sty
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/generic/iftex\iftex.sty))
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/geometry\geometry.cfg)

Package geometry Warning: Over-specification in h'-direction. width' (5058.9pt) is ignored.

Package geometry Warning: Over-specification in v'-direction. height' (5058.9pt) is ignored.

)
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/l3backend\l3backend-dvi
ps.def) (c6461476dd8de54b1e07f6b0e45f144a.aux)
geometry driver: auto-detecting
geometry detected driver: dvips
(C:\Users\steph\AppData\Local\Programs\MiKTeX\tex/latex/psnfss\ot1phv.fd)
! You can't use `macro parameter character #' in horizontal mode.
l.14 ...{10.500000}{\sffamily HR Response Animal #
2}
No pages of output.
Transcript written on c6461476dd8de54b1e07f6b0e45f144a.log.

No such file or directory: 'latex': 'latex'

I have this error message:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in post_execute()
    107             def post_execute():
    108                 if matplotlib.is_interactive():
--> 109                     draw_all()
    110 
    111             # IPython >= 2

~/anaconda3/lib/python3.7/site-packages/matplotlib/_pylab_helpers.py in draw_all(cls, force)
    130         for f_mgr in cls.get_all_fig_managers():
    131             if force or f_mgr.canvas.figure.stale:
--> 132                 f_mgr.canvas.draw_idle()
    133 
    134 atexit.register(Gcf.destroy_all)

~/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in draw_idle(self, *args, **kwargs)
   1897         if not self._is_idle_drawing:
   1898             with self._idle_draw_cntx():
-> 1899                 self.draw(*args, **kwargs)
   1900 
   1901     def draw_cursor(self, event):

~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1185         ticks_to_draw = self._update_ticks(renderer)
   1186         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
-> 1187                                                                 renderer)
   1188 
   1189         for tick in ticks_to_draw:

~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in _get_tick_bboxes(self, ticks, renderer)
   1123         for tick in ticks:
   1124             if tick.label1On and tick.label1.get_visible():
-> 1125                 extent = tick.label1.get_window_extent(renderer)
   1126                 ticklabelBoxes.append(extent)
   1127             if tick.label2On and tick.label2.get_visible():

~/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
    928             raise RuntimeError('Cannot get window extent w/o renderer')
    929 
--> 930         bbox, info, descent = self._get_layout(self._renderer)
    931         x, y = self.get_unitless_position()
    932         x, y = self.get_transform().transform_point((x, y))

~/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in _get_layout(self, renderer)
    311                 w, h, d = renderer.get_text_width_height_descent(clean_line,
    312                                                         self._fontproperties,
--> 313                                                         ismath=ismath)
    314             else:
    315                 w, h, d = 0, 0, 0

~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    207             fontsize = prop.get_size_in_points()
    208             w, h, d = texmanager.get_text_width_height_descent(
--> 209                 s, fontsize, renderer=self)
    210             return w, h, d
    211 

~/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    462         else:
    463             # use dviread. It sometimes returns a wrong descent.
--> 464             dvifile = self.make_dvi(tex, fontsize)
    465             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
    466                 page = next(iter(dvi))

~/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in make_dvi(self, tex, fontsize)
    326                 self._run_checked_subprocess(
    327                     ["latex", "-interaction=nonstopmode", "--halt-on-error",
--> 328                      texfile], tex)
    329             for fname in glob.glob(basefile + '*'):
    330                 if not fname.endswith(('dvi', 'tex')):

~/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex)
    296             report = subprocess.check_output(command,
    297                                              cwd=self.texcache,
--> 298                                              stderr=subprocess.STDOUT)
    299         except subprocess.CalledProcessError as exc:
    300             raise RuntimeError(

~/anaconda3/lib/python3.7/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    393 
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 
    397 

~/anaconda3/lib/python3.7/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    470         kwargs['stderr'] = PIPE
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:
    474             stdout, stderr = process.communicate(input, timeout=timeout)

~/anaconda3/lib/python3.7/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

~/anaconda3/lib/python3.7/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1520                         if errno_num == errno.ENOENT:
   1521                             err_msg += ': ' + repr(err_filename)
-> 1522                     raise child_exception_type(errno_num, err_msg, err_filename)
   1523                 raise child_exception_type(err_msg)
   1524 

FileNotFoundError: [Errno 2] No such file or directory: 'latex': 'latex'

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

~/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
    242 
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    126 
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

~/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2047                         orientation=orientation,
   2048                         dryrun=True,
-> 2049                         **kwargs)
   2050                     renderer = self.figure._cachedRenderer
   2051                     bbox_artists = kwargs.pop("bbox_extra_artists", None)

~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    508 
    509         """
--> 510         FigureCanvasAgg.draw(self)
    511         renderer = self.get_renderer()
    512 

~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1185         ticks_to_draw = self._update_ticks(renderer)
   1186         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
-> 1187                                                                 renderer)
   1188 
   1189         for tick in ticks_to_draw:

~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in _get_tick_bboxes(self, ticks, renderer)
   1123         for tick in ticks:
   1124             if tick.label1On and tick.label1.get_visible():
-> 1125                 extent = tick.label1.get_window_extent(renderer)
   1126                 ticklabelBoxes.append(extent)
   1127             if tick.label2On and tick.label2.get_visible():

~/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in get_window_extent(self, renderer, dpi)
    928             raise RuntimeError('Cannot get window extent w/o renderer')
    929 
--> 930         bbox, info, descent = self._get_layout(self._renderer)
    931         x, y = self.get_unitless_position()
    932         x, y = self.get_transform().transform_point((x, y))

~/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in _get_layout(self, renderer)
    311                 w, h, d = renderer.get_text_width_height_descent(clean_line,
    312                                                         self._fontproperties,
--> 313                                                         ismath=ismath)
    314             else:
    315                 w, h, d = 0, 0, 0

~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    207             fontsize = prop.get_size_in_points()
    208             w, h, d = texmanager.get_text_width_height_descent(
--> 209                 s, fontsize, renderer=self)
    210             return w, h, d
    211 

~/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    462         else:
    463             # use dviread. It sometimes returns a wrong descent.
--> 464             dvifile = self.make_dvi(tex, fontsize)
    465             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
    466                 page = next(iter(dvi))

~/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in make_dvi(self, tex, fontsize)
    326                 self._run_checked_subprocess(
    327                     ["latex", "-interaction=nonstopmode", "--halt-on-error",
--> 328                      texfile], tex)
    329             for fname in glob.glob(basefile + '*'):
    330                 if not fname.endswith(('dvi', 'tex')):

~/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex)
    296             report = subprocess.check_output(command,
    297                                              cwd=self.texcache,
--> 298                                              stderr=subprocess.STDOUT)
    299         except subprocess.CalledProcessError as exc:
    300             raise RuntimeError(

~/anaconda3/lib/python3.7/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    393 
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 
    397 

~/anaconda3/lib/python3.7/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    470         kwargs['stderr'] = PIPE
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:
    474             stdout, stderr = process.communicate(input, timeout=timeout)

~/anaconda3/lib/python3.7/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

~/anaconda3/lib/python3.7/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1520                         if errno_num == errno.ENOENT:
   1521                             err_msg += ': ' + repr(err_filename)
-> 1522                     raise child_exception_type(errno_num, err_msg, err_filename)
   1523                 raise child_exception_type(err_msg)
   1524 

FileNotFoundError: [Errno 2] No such file or directory: 'latex': 'latex'

Plotting will take a long time

When I use this style, I find it takes a very long time (more than 20 seconds in my i7 computer) to plot even a small figure. I think the possible reason is the latex postprocessing procedure. Do you have any idea to reduce the plotting time? Thank you in advance!

missing font metrics file: cmr10

I installed this package with pip on a centos system.
An error occured:
"FileNotFoundError: missing font metrics file: cmr10"
Then, I installed cmr10.ttf no my computer, but nothing changed.
How can I fix this error? Thanks!

Special characters are not showing in X or Y axis

In the code I defined:
plt.ylabel('Trusted Nodes (%)')
But in the plot, It's not showing the % sign, Instead showing Trusted Nodes ( . I think same issue happens with some other sign like #,$.
Uing the default Matplotlib theme, these signs are easily viewable in the X or Y axis depending on how you define in the code.

Matplotlib warning about no LaTeX-compatible font.

Hi,

Whenever I use this package setting

plt.style.use(["science"])
plt.style.reload_library()

I get the following warning sign multiple times when I plot anything:

matplotlib.texmanager - INFO - No LaTeX-compatible font found for the serif font family in rcParams. Using default.

Now, I have investigated a little, this warning is issued here:

https://github.com/matplotlib/matplotlib/blob/02af61b3000b93efad98f415b4a7eb330c9e46c1/lib/matplotlib/texmanager.py#L124

so it looks like it cannot found the specified font in the attribute TexManager.font_info. I have printed the font that is trying to look at, and it is "Times New Roman", as you would expect, but indeed that font is not found in the font_info dictionary:

https://github.com/matplotlib/matplotlib/blob/02af61b3000b93efad98f415b4a7eb330c9e46c1/lib/matplotlib/texmanager.py#L62

What am I missing here? I am using:

SciencePlots: latest commite release
Matplotlib: 3.3.0
OS: Manjaro 20.2
Tex: Texlive installation with these packages:

texlive-bibtexextra
texlive-core
texlive-fontsextra
texlive-formatsextra
texlive-games
texlive-humanities
texlive-latexextra
texlive-music
texlive-pictures
texlive-pstricks
texlive-publishers
texlive-science

Thank you very much for your help!

Crashes with under_score (LaTeX literals are not handled properly)

SciencePlots 1.0.3

fig, ax = plt.subplots()
ax.plot([1, 2, 1.5], color='r')
ax.set(ylabel="under_score", xlabel="x")
fig.tight_layout()

The LaTeX process crashes:


RuntimeError: latex was not able to process the following string:
b'under_score'

Here is the full report generated by latex:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017) (preloaded format=latex)
 restricted \write18 enabled.
entering extended mode
($HOME/.matplotlib/tex.cache/736484790cd7b3da687be023bfb15307.tex
LaTeX2e <2017-04-15>
Babel <3.10> and hyphenation patterns for 84 language(s) loaded.
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/size10.clo))
(/usr/local/texlive/2017/texmf-dist/tex/latex/type1cm/type1cm.sty)
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/textcomp.sty
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/ts1enc.def))
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/inputenc.sty
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/utf8.def
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/t1enc.dfu)
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/ot1enc.dfu)
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/omsenc.dfu)
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/ts1enc.dfu)))
(/usr/local/texlive/2017/texmf-dist/tex/latex/amsmath/amsmath.sty
For additional information on amsmath, use the `?' option.
(/usr/local/texlive/2017/texmf-dist/tex/latex/amsmath/amstext.sty
(/usr/local/texlive/2017/texmf-dist/tex/latex/amsmath/amsgen.sty))
(/usr/local/texlive/2017/texmf-dist/tex/latex/amsmath/amsbsy.sty)
(/usr/local/texlive/2017/texmf-dist/tex/latex/amsmath/amsopn.sty))
(/usr/local/texlive/2017/texmf-dist/tex/latex/geometry/geometry.sty
(/usr/local/texlive/2017/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/local/texlive/2017/texmf-dist/tex/generic/oberdiek/ifpdf.sty)
(/usr/local/texlive/2017/texmf-dist/tex/generic/oberdiek/ifvtex.sty)
(/usr/local/texlive/2017/texmf-dist/tex/generic/ifxetex/ifxetex.sty)

Package geometry Warning: Over-specification in `h'-direction.
    `width' (5058.9pt) is ignored.


Package geometry Warning: Over-specification in `v'-direction.
    `height' (5058.9pt) is ignored.

) (./736484790cd7b3da687be023bfb15307.aux)
(/usr/local/texlive/2017/texmf-dist/tex/latex/base/ts1cmr.fd)
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Missing $ inserted.
<inserted text> 
                $
l.14 ...ize{12.000000}{15.000000}{\rmfamily under_
                                                  score}
No pages of output.
Transcript written on 736484790cd7b3da687be023bfb15307.log.

It needs to be escaped as under\_score. FYI, it does not handle some special characters like $, #, %` --- it must be escaped.

Also, I don't see why the error message is about b'under_score'. Unicode handling is wrong too somewhere. FYI I am using python3.

LaTeX Error: File `amsmathamssymb.sty' not found.

Hi, I tried to run the code with both MikTex and TexLive. I got the same error. I am unable to trace the origin of the issue and fix it, but it looks like its coming because of a line somewhere like \usepackage{amsmathamssymb.sty} instead of \usepackage{amssymb, amsmath}. How can I fix this please?

I am using SciencePlots 1.08, matplotlib 3.0.3andpython 3.6` on Windows 10.

Part of the error traceback

RuntimeError: latex was not able to process the following string:
b'lp'

Here is the full report generated by latex:
This is pdfTeX, Version 3.141592653-2.6-1.40.22 (MiKTeX 21.6)
entering extended mode
(C:/Users/rhk217/.matplotlib/tex.cache/095cf47b971237f6261701feb16a758d.tex
LaTeX2e <2021-06-01>
L3 programming layer <2021-06-01>
(D:/Program Files/MiKTeX\tex/latex/base\article.cls
Document Class: article 2021/02/12 v1.4n Standard LaTeX document class
(D:/Program Files/MiKTeX\tex/latex/base\size10.clo))
(D:/Program Files/MiKTeX\tex/latex/type1cm\type1cm.sty)
(D:/Program Files/MiKTeX\tex/latex/base\textcomp.sty)
(D:/Program Files/MiKTeX\tex/latex/base\inputenc.sty)

! LaTeX Error: File `amsmathamssymb.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.
<read *>

l.12 \usepackage
                [papersize={72in,72in},body={70in,70in},margin={1in,1in}]{ge...
No pages of output.
Transcript written on 095cf47b971237f6261701feb16a758d.log.
latex: major issue: So far, you have not checked for MiKTeX updates.

Cannot find latex

When I run the demo, there has been an error called: RuntimeError: Failed to process string with tex because latex could not be found

Grid below graph

Currently the grid is plotted on top of the graph:
image
It looks cleaner if the grid is below the graph:
image
This can be done by adding axes.axisbelow : True to the grid.mplstyle

Change default param

Hi, @garrettj403 !

I have some question: can i use my custom plotting params instead of plotting params in science.mplstyle?
i.e.

plt.style.use(['science'])

plt.subplots_adjust(
    left=0.04,
    bottom=0.08,
    right=0.98,
    top=0.9,
    wspace=0.16,
    hspace=0.27
)

or not?

Default image size in science.mplstyle very small:)

Sincerely yours, Kirill

pip installing fails

Can't seem to install using pip install SciencePlots

pip install SciencePlots
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
Defaulting to user installation because normal site-packages is not writeable
Collecting SciencePlots
  Downloading SciencePlots-1.0.5.tar.gz (6.5 kB)
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-Kd_C4X/scienceplots/setup.py'"'"'; __file__='"'"'/tmp/pip-install-Kd_C4X/scienceplots/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-h_pH6o
         cwd: /tmp/pip-install-Kd_C4X/scienceplots/
    Complete output (5 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-Kd_C4X/scienceplots/setup.py", line 22, in <module>
        with open(os.path.join(root, 'README.md'), 'r', encoding='utf-8') as f:
    TypeError: 'encoding' is an invalid keyword argument for this function
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

About use this tool in win10 with RuntimeError

First, thanks for @garrettj403 perfect work, it is very useful.


If not install LaTeX in win10, run examples in this repo will get an error:
"RuntimeError: Failed to process string with tex because latex could not be found"


Just need to install LaTeX and add 'path\texstudio.exe' to systerm enviroment PATH
(Note1: Need to install MiKTex and LaTeX, The following installation package will provide guidelines.)
(Note2: Selecting for all users when installing MiKTex will automatically add MiKTex to the system environment variables PATH)


the tex download: http://www.tug.org/


I tested this tool in Jupyter notebook and it works very well.
I hope this suggestion can help friends who encounter this problem.

How to use it in anaconda

I install this library through "pip intsall SciencePlots" use conda base environment, but i check the matplotlib style file, it does not include the SciencePlots syle file.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.