I want to plot with latex and other fonts but only latex font seems to be available. How can I enable other fonts with usetex?
import numpy as np
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('font', family='Arial')
plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()
Plotted image
Using usetex=True
You have to use your own LaTeX header for matplotlib.
You can then use the fontpackages to select fonts.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.unicode'] = True
plt.rcParams['text.latex.preamble'] = r'''
\usepackage{mathtools}
\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}
% more packages here
'''
plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')
Result:
using the pgf backend
You get the most flexibility by using the pgf backend. This needs a recent LaTeX installation in the system.
For me, the most practical approach is to have a matplotlibrc and a header-matplotlib.tex and just include the texfile in the matplotlibrc. However, because matplotlib runs tex in a tmp directory, you need to add the current directory to the TEXINPUTS.
Example:
matplotlibrc
backend: pgf # use the pgf backend
pgf.rcfonts : False # setup the fonts yourself in the header
text.usetex : True
text.latex.unicode : True
pgf.texsystem : lualatex
pgf.preamble : \input{header-matplotlib.tex}
header-matplotlib.tex
\usepackage{fontspec}
\setsansfont{Arial} # for the example I used Fira Sans
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{unicode-math}
\setmathfont{Latin Modern Math}
% more packages here
pgf_plot.py (This got much smaller, as we are setting the options in `matplotlibrc)
import matplotlib.pyplot as plt
import numpy as np
plt.imshow(np.random.randn(100, 100))
plt.title('This is a test')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.savefig('test.pdf')
Run using
$ TEXINPUTS=$(pwd): python pgf_plots.py
Result:
This approach can be extended, to match the fonts and font size of the plot to the ones used in your document, see the example here:
https://github.com/Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE/tree/master/examples/use_system_latex
Related
I have tried to install xkcd fonts 'Humor Sans', but unfortunately, I am not able to use the fonts. Here, is what I did so far:
iPad Pro
installed carnets and juno (for Jupyter notebooks)
Matplotlib version 3.1.1
installed iFonts to install Humor Sans
run xkcd examples, e.g.
%pylab inline
plt.xkcd()
plt.plot(sin(linspace(0,10)))
plt.title('Whoo Hoo!!!')
The plot, with the exception of the fonts is working as expected. The error message gives me, what I expected:
findfont: Font family ['xkcd', 'xkcd Script', 'Humor Sans', 'Comic Sans MS'] not found. Falling back to DejaVu Sans.
The font manager does not find any Humor* Sans although in the Settings -> General -> Fonts, I do find the fonts.
import matplotlib.font_manager
x = [f.name for f in matplotlib.font_manager.fontManager.ttflist if f.name.startswith('Humor')]
print(set(x))
the outcome is an empty result:
set()
Since, the folder structure is not clear using the iPad, i have copied the HumorSans.ttf file in a folder "Fonts", e.g.
import matplotlib.font_manager as fm
import matplotlib.pyplot as plot
import numpy as np
font_path = 'Fonts/Humor-Sans.ttf'
my_font = fm.FontProperties(fname=font_path)
plt.xkcd()
fig, ax = plt.subplot()
x = np.linspace(0,3)
y = np.sin(x)
ax.bar(x, y, color='green')
ax.set_xlabel(u'Some x label', fontproperties=my_font)
ax.set_ylabel(u'Some y label', fontproperties=my_font)
ax.set_title(u'Some fancy title', fontproperties=my_font)
for label in ax.get_xticklabels():
label.set_fontproperties(my_font)
This works as expected. The fonts is the Humor Sans fonts, where I have explicitly changed the fonts. For all other texts, e.g. yticklabels, the fonts is the standard fonts such that the problem is still there.
How can I correctly install, either directly or load in each notebook the fonts. The problem is that i don't have access to the folders, I need to work in, e.g. matplotlib.get_cachedir()
/private/var/mobile/Containers/Data/Application/AAD3....5693/tmp/matplotlib-nu6taz9_
Any help?
Solved!
Luke Davis Helped with his post: How can I configure matplotlib to be able to read fonts from a local path?
#!/usr/bin/env python3
# Imports
import os
import re
import shutil
from glob import glob
from matplotlib import matplotlib_fname
from matplotlib import get_cachedir
# Copy files over
_dir_data = re.sub('/matplotlibrc$', '', matplotlib_fname())
dir_source = '<your-font-directory-here>'
dir_dest = f'{_dir_data}/fonts/ttf'
# print(f'Transfering .ttf and .otf files from {dir_source} to {dir_dest}.')
for file in glob(f'{dir_source}/*.[ot]tf'):
if not os.path.exists(f'{dir_dest}/{os.path.basename(file)}'):
print(f'Adding font "{os.path.basename(file)}".')
shutil.copy(file, dir_dest)
# Delete cache
dir_cache = get_cachedir()
for file in glob(f'{dir_cache}/*.cache') + glob(f'{dir_cache}/font*'):
if not os.path.isdir(file): # don't dump the tex.cache folder... because dunno why
os.remove(file)
print(f'Deleted font cache {file}.')
I am following a python tutorial about the use of plotly.
Here are some commands I have to run to import functions and methods I will use
import plotly.plotly as py
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
However, when I run commands on my jupyter nootbook, it says the use of plotly is deprecated and it recommends me to use the module chart_studio instead (error points to line import plotly.plotly as py):
ImportError: The plotly.plotly module is deprecated, please install
the chart-studio package and use the chart_studio.plotly module
instead.
So I run
pip install chart_studio
and try to replace the line above with functions and methods coming from the chart_studio module.
Here is my code:
import chart_studio.plotly as py
import plotly.graph_objects as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
data = dict(type= 'cloropleth',
locations = ['AZ','CA','NY'],
locationmode = 'USA-states',
colorscale = 'Portland',
text = ['text 1','text 2','text 3'],
z = [1,2,3],
colorbar = {'Title':'Colorbar title goes here'})
mylayout = dict(geo={'scope':'usa'})
choromap = go.Figure(data = [data], layout=mylayout, skip_invalid=True)
iplot(choromap)
The problem is that, when running the final line iplot(choromap), I get this empty graph
While in the tutorial this other graph appears
What is wrong?
Please note that I installed cufflinks-0.17.3 plotly-4.5.4
Did you try to cleanly install plotly?
Uninstall plotly using pip
!pip uninstall plotly
Then uninstall plotly using conda
!conda uninstall plotly
After that, install the last version using pip
!pip install plotly
check Plotly version
import plotly
plotly.__version__
SOLVED
In my code there were 2 errors:
at line
type= 'cloropleth',
I had the mispelled value 'cloropleth', where the correct value is 'choropleth',
and then at line
colorbar = {'Title':'Colorbar title goes here'})
I had 'Title', where the correct key is 'title' (lowercase).
Fixed them and now the map is correctly displayed.
Also, it was not necessary to install chart_studio.
So in the end the correct code is:
import plotly.graph_objects as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
data = dict(type= 'choropleth',
locations = ['AZ','CA','NY'],
locationmode = 'USA-states',
colorscale = 'Portland',
text = ['text 1','text 2','text 3'],
z = [1,2,3],
colorbar = {'title':'Colorbar title goes here'})
mylayout = dict(geo={'scope':'usa'})
choromap = go.Figure(data = [data], layout=mylayout)
iplot(choromap)
been playing around with plotly for Python, but constantly running into the same error message stated above. I installed plotly on Anaconda, getting the error message both on Jupyter and Spyder respectively:
#data manipulation
import pandas as pd
import numpy as np
#loading csv
df = df = pd.read_csv(r'C:\Users\hendev\Desktop\FIFA18 - Ultimate Team players.csv')
import plotly.graph_objs as go
# prepare data
x2017 = df.overall[df.added_date == 2017]
x2018 = df.overall[df.added_date == 2018]
trace1 = go.Histogram(
x=x2017,
opacity=0.75,
name = "2017",
marker=dict(color='rgba(171, 50, 96, 0.6)'))
trace2 = go.Histogram(
x=x2018,
opacity=0.75,
name = "2018",
marker=dict(color='rgba(12, 50, 196, 0.6)'))
data = [trace1, trace2]
layout = go.Layout(barmode='overlay',
title=' Rating added in 2017 and 2018',
xaxis=dict(title='students-staff ratio'),
yaxis=dict( title='Count'),
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)
Any idea what I'm doing wrong?
Note: $ from plotly.plotly import iplot will work only till plotly v3.10.0 The plotly.plotly module has been deprecated in plotly v4.0. Check your version first:
$ python3 -c 'import plotly; print(plotly.__version__)' # for Python 3
$ python -c 'import plotly; print(plotly.__version__)' # for Python 2
v4.0 onwards, the functionality has been split into two modes: online and offline.
Online
If you wish to have the figures rendered online, you will now need to import chart-studio and use
from chart_studio.plotly import plot, iplot
Offline
If you want to render the images locally, you have multiple options:
from plotly.offline import iplot
# your code
iplot(fig)
or
from plotly.subplots import make_subplots
fig = make_subplots(# your args)
# your code
fig.show()
or
import plotly.io as pio
# your code
pio.show(fig)
or
import plotly.graph_objects as go
fig = go.Figure(# your args)
# your code
fig.show()
You can read up more on the renderers here.
You forgot to import it
from plotly.plotly import iplot
You need to call iplot with py:
import plotly.plotly as py
py.iplot(fig)
Just in case, if you want to plot in offline mode and save plot as file.hmtl:
import plotly.offline as py
plotly.offline.init_notebook_mode()
py.iplot(fig, filename="file.html")
Do not be afraid of looking through in documentation: here you can find nice and understandable examples how to use plotly properly. For example, here you can see how to plot simple bar chart, etc.
For Jupyter Notebook and Kaggle Notebooks, this helped me.
from plotly.offline import iplot
The following piece of code works fine when I run the script in pycharm
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as mpatches
c1 = mpatches.Patch(color="green",label="No Traffic")
c2 = mpatches.Patch(color="red",label="Traffic")
df = predict_df.limit(100).toPandas()
colors = {0:"red",1:"green"}
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(df["avgSpeed"],df["vehicleCount"],df["avgMeasuredTime"],c=df["prediction"].apply(lambda x: colors[x]),s=100,marker="o")
ax.set_xlabel('avgMeasuredTime')
ax.set_ylabel('avgSpeed')
ax.set_zlabel('vehicleCount')
plt.title("BiKmeans Traffic Data")
plt.legend(handles=[c1,c2])
plt.show()
I have installed matplotlib using pip, also based on some similar questions tried to install as sudo apt-get install python-matplotlib
but I get the same error in Zepplin,
File "/home/benjamin/.local/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 280, in <lambda>
key=lambda col: col.do_3d_projection(renderer), AttributeError: 'PathCollection' object has no attribute 'do_3d_projection'
The version of matplotlib is 2.2.0
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it?
%pyspark
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
And here is the error I've got
Traceback (most recent call last):
File "/tmp/zeppelin_pyspark-3580576524078731606.py", line 235, in <module>
eval(compiledCode)
File "<string>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/matplotlib/pyplot.py", line 78, in <module>
new_figure_manager, draw_if_interactive, show = pylab_setup()
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtk.py", line 8, in <module>
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
_init()
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
I also try to add these lines, but still cannot work
import matplotlib
matplotlib.use('Agg')
The following works for me with Spark & Python 3:
%pyspark
import matplotlib
import io
# If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect.
# see: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def show(p):
img = io.StringIO()
p.savefig(img, format='svg')
img.seek(0)
print("%html <div style='width:600px'>" + img.getvalue() + "</div>")
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
show(plt)
The Zeppelin documentation suggests that the following should work:
%python
import matplotlib.pyplot as plt
plt.figure()
(.. ..)
z.show(plt)
plt.close()
This doesn't work for me with Python 3, but looks to be addressed with the soon-to-be-merged PR #1213.
Note that as of Zeppelin 0.7.3, matplotlib integration is much more seamless, so the methods described here are no longer necessary. https://zeppelin.apache.org/docs/latest/interpreter/python.html#matplotlib-integration
As per #eddies suggestion, I tried and this is what worked for me on Zeppelin 0.6.1 python 2.7
%python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.figure()
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
z.show(plt, width='500px')
plt.close()
Change this:
import matplotlib
matplotlib.use('Agg')
with
import matplotlib.pyplot as plt; plt.rcdefaults()
plt.switch_backend('agg')
Complete code example Spark 2.2.0 + python3(anaconda3.5):
%spark.pyspark
import matplotlib.pyplot as plt; plt.rcdefaults()
plt.switch_backend('agg')
import numpy as np
import io
def show(p):
img = io.StringIO()
p.savefig(img, format='svg')
img.seek(0)
print ("%html <div style='width:600px'>" + img.getvalue() + "</div>")
# Example data
people=('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos=np.arange(len(people))
performance=3 + 10 * np.random.rand(len(people))
error=np.random.rand(len(people))
plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, people)
plt.xlabel('Performance')
plt.title('How fast do you want to go today?')
show(plt)
I would suggest you to use IPython/IPySpark interpreter in zeppelin 0.8.0 which will be released soon. The matplotlib integration in ipython is almost the same as jupyter. There's one tutorial https://www.zepl.com/viewer/notebooks/bm90ZTovL3pqZmZkdS9lN2Q3ODNiODRkNjA0ZjVjODM1OWZlMWExZjM4OTk3Zi9ub3RlLmpzb24