Latex colors not rendered in matplotlib text - python

Tex's \textcolor seems to be ignored in my plottling script
import matplotlib as matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'text.usetex': True})
matplotlib.rc(
'text.latex', preamble=r"\usepackage{xcolor}")
fig, ax = plt.subplots()
ax.set_ylabel(r'\textcolor{red}{aaaaaaa}')
plt.show()
does not give me a red text, it produces:
Am I missing something?

It's explained in more detail here : https://matplotlib.org/users/usetex.html but seems like it only works when you export it to a ps file. For me, it works in color if you're saving it as a ps file while the same file inline doesn't work.
Slight workaround here.
import matplotlib as matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'text.usetex': True})
matplotlib.rc('text.latex', preamble=r"\usepackage{xcolor}")
fig, ax = plt.subplots()
ax.set_ylabel(r"aaaaaaa", color='r')
#plt.savefig(r"foo.ps")
# you can include the above line if you're using your old code.
plt.show()

Related

Y-axis scientific notation formatter lost when convert matplotlib figure into html with mpld3

I am trying to convert a figure created with matplotlib into html to embed it into a web page with mpld3.fig_to_html method. For some reasons, the scientific notation is lost on the y-axis. If I try to save a local .png image the scientific notation is shown correctly.
Moreover if I save a local .html file with mpld3.save_html the scientific notation is lost as well.
Any idea ?
Here's an example:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import mpld3
from matplotlib import ticker
t = [130940239,30492094,20394029]
s = [3898298328,3498328998234,39482]
fig, ax = plt.subplots()
formatter1 = ticker.ScalarFormatter(useMathText=True)
formatter1.set_scientific(True)
formatter1.set_powerlimits((0, 0))
ax.yaxis.set_major_formatter(formatter1)
ax.plot(t, s)
html_str = mpld3.fig_to_html(fig)
ax.grid()
mpld3.save_html(fig,"test_dummy.html")
fig.savefig("test.png")

My plot bar graph isn't showing up. What's wrong with my code

import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
%matplotlib notebook
plt.figure(figsize=(12, 6))
CasData.pivot(index='year', columns='CasualtyNumber', values='People').plot(kind='bar')
plt.title('Casualties per year')
plt.xlabel('Year', fontsize=5)
plt.ylabel('Number of Casualties')
plt.show()
My plot bar graph using matplotlib.pyplot isn't showing.
I don't know why but my bar graph isn't showing. I've tried different ways.
If someone could help me out please. I'd appreciate it. Thank you.
Remove the line %matplotlib notebook.
It is overriding the previous line (these two lines are setting the backend). inline returns static plots, notebook is used for interactivity.
You also do not need the plt.show() line. This is taken care of by the inline backend.
This answer explains more about the backends: https://stackoverflow.com/a/43028034/6709902
I'm not really sure about your code as it seems incomplete but if you're using pivot I assumed you're pulling the data from a ".csv" file.
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib notebook
CasData = pd.read_csv('data.csv')
CasData.pivot_table(index='year', columns='CasualtyNumber', values='People').plot(kind='bar')
plt.title('Casualties per year')
plt.xlabel('Year',fontsize='5')
plt.ylabel('Number of Casualties')
plt.show()
You need to provide the data in order to plot something and I don't
see you providing any.

Python candlestick chart can not show

I executed the code below and no errors showed in the process, but plt.show() could not work and showed nothing in the end! I'm confused and want to know why......
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import quandl
df = quandl.get("EOD/AAPL", authtoken="fzTPb-TWywaPkbdAS1VF")
df['Date'] = df.index.map(mdates.date2num)
ohlc = df[['Date','Open','High','Low','Close']]
f1, ax = plt.subplots(figsize = (10,5))
candlestick_ohlc(ax, ohlc.values, width=.6, colorup='green', colordown='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.show()
In jupyter notebook it makes sense to define a backend, e.g. %matplotlib inline or %matplotlib notebook.
When then running your code in a singe cell it should show you the plot.
If you need to run it in seperate cells, plt.show() will not know what to show from previous cells. So in that case, state the figure instead,
f1
to show the figure f1.

Axis spikes not showing up on Matplotlib plots

I am trying to plot a couple of line graphs using Matplotlib and the small dashes which marks the center of the xticks are not showing up. Here is a sample plot I found online which has the marks (I circled them).
Now below is my code and the graph. I know it's not related to spines.
Code:
from sklearn.externals import joblib
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import math
sns.set()
sns.set_style("dark")
sns.set_style("white")
plt.figure()
plt.plot([1,2,3,4,5],[10,5,69,38,52],label='test')
plt.xticks([1,2,3,4,5],['apple','orange','grapes','lemon','pear'],ha='right')
plt.xticks(rotation=45)
plt.savefig("test.png", dpi=300)
OS: MacOX High Sierra 10.13, Python: 3.6.0 and no Virtual Environments
You can customise the seaborn styles to add back ticks (there is also a style for ticks). See here for the full details.
Just change your set_style line to have a second parameter which is a dictionary of overrides. In this case it is setting the size of the xticks. That link gives the full details of built-in styles and all the options for overriding.
sns.set_style("white", {"xtick.major.size": 5})

Scientific Notation in matplotlib inline plots in jupyter

I am plotting values that are of order 10^-8 and I would like my inline plot in jupyter to output the yaxis ticks in that (scientific) notation. I tried :
plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.1E'))
as well as
plt.gca().yaxis.get_major_formatter().set_powerlimits((0, -10))
and
plt.ticklabel_format(style='sci')
but nothing seems to work. What am I doing wrong? I have the following example:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import mpld3
mpld3.enable_notebook()
import matplotlib.ticker as mtick
a=5*10**-8
b=3*10**-8
x=np.arange(0,10,0.01)
y=a*x+b
plt.figure(figsize=(12,5))
plt.subplot(1,2,1)
plt.plot(x,y)
# plt.ticklabel_format(style='sci')
# plt.gca().yaxis.get_major_formatter().set_powerlimits((0, -10))
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))
plt.show()
Any pointers would be helpful as I don't find anything on this, besides ticks format of an axis in matplotlib, enter link description here or Change x axes scale in matplotlib
NOTE: If I comment out the lines with import mpld3 and mpld3.enable_notebook() then it works but cannot interact with the plot... Is there some special treatment of matplotlib when plotting inline in jupyter?
Thanks!
You can use set_yticklabels to have a similar looking output.
ax = plt.gca()
ax.set_yticklabels(['10^-8','2*10^-8','3*10^-8','4*10^-8'])

Categories