Matplotlib: emoji font does not work when using backend_pdf - pdf

I want to use the emoji-font "Symbola.ttf" to label my plots. This does work when I use plt.show(). But it does not work when using the backend_pdf. Only two emojis are shown in a mixed up order.
example images:
when using plt.show():
when using the backend_pdf:
example code:
Here is my code to produce these examples:
import matplotlib.backends.backend_pdf
import matplotlib.pyplot as plt
import emoji
from matplotlib.font_manager import FontProperties
emojis = [emoji.EMOJI_UNICODE[e] for e in list(emoji.EMOJI_UNICODE.keys())[620:630]]
prop = FontProperties(fname='./Symbola.ttf', size=30)
# backend_pdf plot
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
plt.xticks(range(len(emojis)), emojis, fontproperties=prop)
pdf.savefig()
pdf.close()
# plt.show() plot
plt.xticks(range(len(emojis)), emojis, fontproperties=prop)
plt.show()
I'm running this on a Linux machine.

I think I have found the problem. It seems that my Symbola.ttf was broken. When I use this .ttf file everything works great.

Related

Matplotlib graph does not show in Python Interactive Window

The following is my code, but I can't get the plot to show on my Visual Studio Code even though I am running this on the Python Interactive Window, which should usually show a graph plot after running. The tables are showing just fine. I also do not get a default graph which pops up like it normally should. What am I doing wrong?
import yfinance as yf
import pandas as pd
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import talib
df = pd.read_csv('filename.csv')
df = df.sort_index()
macd, macdsignal, macdhist = talib.MACD(df['Close'], fastperiod=12, slowperiod=26, signalperiod=9)
macd = macd.to_list()
macdsignal = macdsignal.to_list()
macdhist = macdhist.to_list()
df['macd'], df['macdsignal'], df['macdhist'] = macd,macdsignal,macdhist
ax = plt.gca()
print(df.columns)
df.plot(kind='line',x='Date',y='macd', color='blue',ax=ax)
df.plot(kind='line',x='Date',y='macdsignal', color='red', ax=ax)
plt.show()
The csv file has data that looks like this
The issue was with matplotlib.use('agg'), which does not support the show() function. This prevented the graph from being displayed on Visual Studio's Interactive Window. The matplotlib.use('agg') method can, however, be used for saving your graph in a .png format.
According to Matplotlib.org, agg is "the canonical renderer for user interfaces, which uses the Anti-Grain Geometry C++ library to make a raster (pixel) image of the figure". More information can be found at this link here

Zoom not working on Loading pickled matplotlib Figure

I want to store a matplotlib figure and load it later to use it interactively. To be more specific, I want to be able to use zoom in this figure.
I am using pickle to dump the figure handle into a file.
I then load the figure later using pickle, but the zoom does not work after loading the file even though I can use zoom in the figure before pickling it.
Here's a sample script that illustrates my problem.
import matplotlib.pyplot as plt
import pickle
import numpy as np
import os
import time
# Create Plot Data
x = np.arange(100)
# Create Figure, Axes and plot
fig1,axes1 = plt.subplots()
axes1.plot(x)
# Pickle plot
fileName = os.getcwd() + "/img"\
+ time.asctime(time.localtime()) + ".pickle"
with open(fileName,'wb') as pickle_file:
pickle.dump(fig1,pickle_file)
plt.show() # ZOOM WORKS HERE
plt.close()
# Load pickled plot
with open(fileName,'rb') as read_pickle:
fig_handle = pickle.load(read_pickle)
plt.show() # ZOOM DOES NOT WORK HERE
Zooming into the image before Pickle
Non-Zoomable image after Pickle
Version:
Python 3.7.0
Matplotlib 3.0.0
Pickle 4.0
Is this a limitation with Pickling matplotlib figure? Or is there something I can do to load/dump the figure in a zoomable way?
As #ImportanceOfBeingErnest pointed out I fixed the problem by changing my backends from MacOSX to TkAgg.
Here's what I did.
import matplotlib
matplotlib.get_backend() # Get the current backend
'MacOSX'
# Get Location where configuration file was loaded from.
matplotlib.matplotlib_fname()
'/usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc'
# Edit -> backend:TkAgg
matplotlib.get_backend()
'TkAgg'

How to enable display of Matplotlib graphs with PyCharm?

When I run a program with PyCharm, it doesn't display graphs made with Matplotlib. E.g.:
import matplotlib.pyplot as plt
[...]
plt.imshow(montage(W / np.max(W)), cmap='coolwarm')
I tried calling
plt.interactive(False)
first, but it didn't make a difference.
Running the same program with ipython3, the graphs are displayed.
I set a default back-end for my system in matplotlibrc (TkAgg), and that did the trick.
The below code worked for me:
in pycharm-community-2018.2.2
import matplotlib.pyplot as plt
df.boxplot(column='ApplicantIncome')
plt.show()

matplotlib tex renderer gives unexpected error

I am creating a scatter plot with color map based on some values and I am trying to make part of the x_axis label italic (inspired mostly by this post -> https://stackoverflow.com/a/8384685/1093485) but I am getting a LaTeX error that I can not explain myself, I would appreciate if anyone is able to explain what is going wrong with this chunk?
Minimum code required to reproduce problem here:
#! /usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
X = [1257.422648,1298.449197,1339.475746,1419.475471,1455.52309,1460.50202,1485.533655]
Y = [21.84637515,18.19617016,22.29456694,5.228978612,3.888695726,12.36598466,4.201838517]
Z = [44.02797944,9.758071204,21.58997772,64.53887544,53.09630431,8.461254471,291.4311435]
# Enable LaTeX style
rc('text',usetex=True)
# Plot the data
fig=plt.figure()
fig.patch.set_facecolor('white')
ax=fig.add_subplot(111)
s = ax.scatter(X,Y,c=np.log(Z))
ax.set_xlabel(r'Analyte \textit{m/z}')
ax.xaxis.labelpad = 7.5
cb = plt.colorbar(mappable=s,ax=ax)
plt.show()
Commenting the rc('text',usetex=True) causes the plot to show but obviously without italics. The whole traceback is rather large but seems to revolve around this part (if I read it correctly):
RuntimeError: LaTeX was not able to process the following string:
'$1450$'
Anyone have a suggestion on what to do to isolate the problem?

Annotating a box outside the box, matplotlib

I want the text to appear beside the box instead of inside it:
Here is what I did:
import matplotlib as mpl
import matplotlib.pyplot as plt
from custombox import MyStyle
fig = plt.figure(figsize=(10,10))
legend_ax = plt.subplot(111)
legend_ax.annotate("Text",xy=(0.5,0.5),xycoords='data',xytext=(0.5, 0.5),textcoords= ('data'),ha="center",rotation = 180,bbox=dict(boxstyle="angled, pad=0.5", fc='white', lw=4, ec='Black'))
legend_ax.text(0.6,0.5,"Text", ha="center",size=15)
Here is what it gives me:
Note: custombox is similar to the file that is written in this link:
http://matplotlib.org/1.3.1/users/annotations_guide.html
My ultimate aim is to make it look legend like where the symbol (angled box) appears beside the text that represents it.
EDIT 1: As suggested by Ajean I have annotated text separately but I can't turn of the text within the arrow
One way to do it would be to separate the text and the bbox (which you can reproduce using an arrow). The following gives me something close to what you want, I think.
import matplotlib.pyplot as plt
from matplotlib import patches
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)
ax.annotate("Text", (0.4,0.5))
bb = patches.FancyArrow(0.5,0.5,0.1,0.0,length_includes_head=True, width=0.05,
head_length=0.03, head_width=0.05, fc='white', ec='black',
lw=4)
ax.add_artist(bb)
plt.show()
You can futz with the exact placement as needed. I'm not an expert on all the kwargs, so this may not be the best solution, but it will work.