I want to generate a figure whose title is rendered by LaTeXStrings.jl
However, when I try to use \underline, ValueError is returned.
What should I do?
Sample code is
using PyPlot
using LaTeXStrings
title = L"\underline{\theta}"
fig, ax = subplots()
ax[:plot](randn(100))
ax[:set_title](title, useTex=true)
The error is
PyError (:PyObject_Call) <type 'exceptions.ValueError'>
ValueError(u'\n\\underline{\\theta}\n^\nUnknown symbol: \\underline (at char 0), (line:1, col:1)',)
Adding rc("text", usetex=true) solves the issue
Related
I'd like to express a label on one of my plots in scientific notation. I write it like this in Jupyter:
...
myLabel = $c=0.46 \times 10^{15} cm^2/n_\textrm{eq}$
plt.text(0.55,39,myLabel,fontsize=16)
...
The problem is that the \t character creates a tab and then prints the "imes". Same problem with the \textrm. I've also run into this problem trying to write the greek letter nu, but I got around it with an italic v.
I've googled around and found no good solution. Any fix will be greatly appreciated!
You could try something like this post provides.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True
t = np.linspace(0.0, 1.0, 100)
s = np.cos(4 * np.pi * t) + 2
fig, ax = plt.subplots(figsize=(6, 4), tight_layout=True)
ax.plot(t, s)
ax.set_xlabel(r'\textbf{time (s)}')
ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}', fontsize=16)
ax.set_title(r'\TeX\ is Number $\displaystyle\sum_{n=1}^\infty'
r'\frac{-e^{i\pi}}{2^n}$!', fontsize=16, color='r')
First, set plt.rcParams['text.usetex'] = True. Then, instead of using the $ symbol, try it with r'c=0.46 \times 10^{15} cm^2/n_\textrm{eq}', as in the previous example.
I hope this is helpful!
Could the method "Latex" from the display module of IPython be of service here? (Note that you do need to add quotes to your string definition, and to double you backslashes for them to be left untouched on input):
from IPython.display import Latex
myLabel = "$c=0.46 \\times 10^{15} cm^2/n_{\\textrm{eq}}$"
print(myLabel)
Latex(myLabel)
In a standard colab.research.google.com python notebook, it yields the following result:
My code was working fine and when I tried to run it today without changing anything I got the following error:
TypeError: argmax(): argument 'input' (position 1) must be Tensor, not str
Would appreciate if help could be provided.
below is the code snippet where I am getting an error. I am using BERT mdoel
start_scores, end_scores = model(torch.tensor([input_ids]), # The tokens representing our input text.
token_type_ids=torch.tensor(
[segment_ids])) # The segment IDs to differentiate question from answer_text
# ======== Reconstruct Answer ========
# Find the tokens with the highest `start` and `end` scores.
answer_start = torch.argmax(start_scores)
answer_end = torch.argmax(end_scores)
In your line of code
start_scores, end_scores = model(torch.tensor([input_ids]),token_type_ids=torch.tensor([segment_ids]))
you have to make it:
start_scores, end_scores = model(torch.tensor([input_ids]),token_type_ids=torch.tensor([segment_ids]), return_dict=False).
It worked for me. I had the same problem.
My code is:
snipername = str(input("What's the Sniper's name again?"))
print ("That's right,(snipername)! ")
(snipername) is my varible, but i can't figure out how to print it as well as the message.
Any help would be greatly apprectiated!
Use print("That's right, %s!" % (snipername))
I found this answer
[Octave : How to change line color and width in drawRect
how to change the color in drawRect.
When I try the same for drawArrow, I get:
h=drawArrow(0,0,3,1,1,1,1,1);
h =
scalar structure containing the fields:
body = -12.469
head = -11.925
set(h,'color','r');
error: octave_base_value::array_value():
wrong type argument 'scalar struct'
error: set: H must be a graphics handle
What I am doing wrong here? For me it looks the same.
Thanks
Karl
You really should mention that you are using the octave-forge geometry package. drawArrow returns a struct with handles for the arrow body and head (as shown by your code) so you can and have to set them separately:
pkg load geometry
h = drawArrow (0,0,3,1,1,1,1,1);
set (h.body, "color", "r")
set (h.head, "facecolor", get(h.body, "color"))
You can also set a border around the head with "edgecolor"
I've been trying to embed an animation into an iPython notebook but without success. I'm using the latest version of Enthought Canopy (python 2.7.3) on a Mac running 10.8.5 using Safari as my default browser.
After much failed experimentation, I tried using this code
%pylab inline
from tempfile import NamedTemporaryFile
VIDEO_TAG = """<video controls>
<source src="data:video/x-m4v;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>"""
def anim_to_html(anim):
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.mp4') as f:
anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
video = open(f.name, "rb").read()
anim._encoded_video = video.encode("base64")
return VIDEO_TAG.format(anim._encoded_video)
from IPython.display import HTML
def display_animation(anim):
plt.close(anim._fig)
return HTML(anim_to_html(anim))
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
# call our new function to display the animation
display_animation(anim)
from jake Vanderplas on the web. I installed ffmpeg.
On running the code I get the video progress bar, but no graph, just an empty space above the video progress bar.
After a couple of days of working on this I've not found a solution (the above is the closest I've come to). Can anyone see what's going wrong or suggestions to try?
Many thanks.
This problem is solved in Jessica Hamrick's comment on Jake Vanderplas's blog at https://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
She added added two additional items to the extra_args argument:
extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p']