I am trying to read an image from an SVG file and insert in matplotlib figure.
import matplotlib.pyplot as plt
import pylustrator as pyl
import numpy as np
from matplotlib.figure import Figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from svglib.svglib import svg2rlg
ax = plt.subplot(111)
ax.plot(
[1, 2, 3], [1, 2, 3],
'go-',
label='line 1',
linewidth=2
)
# arr_img = plt.imread("stinkbug.svg")
# arr_img = svg2rlg("stinkbug.svg")
arr_img = pyl.load("stinkbug.svg")
im = OffsetImage(arr_img)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction')
ax.add_artist(ab)
plt.show()
I tried to use pylustratorpost for reading the svg image. The code works when the input image is in png format. But I am not able to add the same image saved in svg extension(image).
I couldn't successfully insert due to the following error,
"float".format(self._A.dtype))
TypeError: Image data of dtype object cannot be converted to float
Suggestions on how to fix this will be really helpful.
Related
[Image here]
1I want to plot mode of as a line that comes from a bunch of lines. But I get value error as follows:
ValueError: x and y must have same first dimension, but have shapes (1, 159) and (2, 1, 159)
How to solve it?
My Code is as follows:
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy import stats
hvsra = []
for filename in glob('*.hv'):
with open(filename) as f:
hv = np.genfromtxt(f)
hv_m = np.ma.array(hv)
new_hv = hv_m[:,0:2]
freq = new_hv[:,0]
freq_new = np.reshape(freq_arr, (1, 159))
amp = new_hv[:,1]
hvsra.append(amp)
hvsr = np.array(hvsra)
hvsrm = stats.mode(hvsr)
plt.figure(figsize=(12, 8))
plt.loglog(freq_new,
hvsrm)
Thanks for your help.
I want to connect two points in a data frame plot with another line and add it to the plot:
import numpy as np
from numpy.random import randn
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
%matplotlib inline
days = [datetime(2016, 1, 1), datetime(2016, 1, 2),datetime(2016, 1, 3),datetime(2016, 1, 4)]
dt_ind = pd.DatetimeIndex(days)
data = np.random.randn(4,2)
cols = ['A','B']
df = pd.DataFrame(data,dt_ind,cols)
df['A'].plot(figsize=(12,4), sort_columns=True)
here is the data frame:
enter image description here
and the plot:
enter image description here
how is that possible? for example add a line from point 2 to point 4 (or any two points)
You want to use matplotlib's plt.subplots() function to return a fig and ax object, so you can then add separate lines to your ax.
import numpy as np
from numpy.random import randn
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
%matplotlib inline
days = [datetime(2016, 1, 1),
datetime(2016, 1, 2),
datetime(2016, 1, 3),
datetime(2016, 1, 4)]
dt_ind = pd.DatetimeIndex(days)
data = np.random.randn(4,2)
cols = ['A','B']
df = pd.DataFrame(data,dt_ind,cols)
fig, ax = plt.subplots()
ax.plot(df['A'], color='red')
ax.plot([df.index[1], df.index[3]],
[df['A'][1], df['A'][3]], color='blue')
I'm trying to plot data in two dataframes in two subplots. I'm referring to this link
import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt
df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))
plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=2)
df1.plot(ax=axes[0, 0], style='o-')
axes[0, 0].set_xlabel('x')
axes[0, 0].set_ylabel('y')
axes[0, 0].set_title('ttl')
df2.plot(ax=axes[0, 1], style='o-')
axes[0, 1].set_xlabel('x')
axes[0, 1].set_ylabel('y')
axes[0, 1].set_title('ttl')
However, I get the following error
df1.plot(ax=axes[0, 0], style='o-')
IndexError: too many indices for array
Any suggestions on how to resolve this will be really helpful.
EDIT: The answer provided below works for 1 row with 2 cols
I'm facing an error for 2 rows and 2 cols
import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt
df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))
df3 = pd.DataFrame(np.random.randn(10, 10))
df4 = pd.DataFrame(np.random.randn(10, 10))
pprint(df1)
plt.figure()
fig, axes = plt.subplots(nrows=2, ncols=2)
df1.plot(ax=axes[0], style='o-')
axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[0].set_title('ttl')
df2.plot(ax=axes[1], style='o-')
axes[1].set_xlabel('x')
axes[1].set_ylabel('y')
axes[1].set_title('ttl')
df3.plot(ax=axes[2], style='o-')
axes[2].set_xlabel('x')
axes[2].set_ylabel('y')
axes[2].set_title('ttl')
df4.plot(ax=axes[3], style='o-')
axes[3].set_xlabel('x')
axes[3].set_ylabel('y')
axes[3].set_title('ttl')
plt.show()
Error:
AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'
Any suggestions?
Axes are one dimensional, you have to do like this:
df1.plot(ax=axes[0], style='o-')
df2.plot(ax=axes[1], style='o-')
I suggest reading this, look at the squeeze parameter and you will understand this is happening.
I just begin with Python, scypi and matplotlib, I had copy this code:
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
data = stats.exponweib.rvs(a=1, c=2.09, scale=10.895, loc=0, size=2500)
plt.plot(data, stats.exponweib.pdf(data, *stats.exponweib.fit(data, 1, 1, scale=02, loc=0))
_ = plt.hist(data, bins = np.linspace(0, 16, 33), normed=True, alpha=0.5)
plt.show()
But it show an error:
'LaTeX was not able to process the following string: b'lp''
The file ...Lib\site-packages\matplotlib\mpl-data\matplotlibrc show:
#text.usetex : False
os : windows 7
dis: winpython
What can I do?
Thanks.
Given this heat map:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
How would I go about making the color bar values display in percent format?
Also, what if I just wanted to show the first and last values on the color bar?
Thanks in advance!
iterating on the solution of #mwaskom, without creating the colorbar yourself:
import numpy as np
import seaborn as sns
data = np.random.rand(8, 12)
ax = sns.heatmap(data, vmin=0, vmax=1)
cbar = ax.collections[0].colorbar
cbar.set_ticks([0, .2, .75, 1])
cbar.set_ticklabels(['low', '20%', '75%', '100%'])
Well, I had a similar problem and figured out how to properly set a formatter. Your example would become something like:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
uniform_data = 100 * uniform_data
sns.heatmap(uniform_data,
cbar_kws={'format': '%.0f%%'})
So, what you have to do is to pass an old-style string formatter to add percentages to colorbar labels. Not exactly what I would name self-evident, but works...
To show only the first and last, then you add vmax, vmin and an extra parameter to cbar_kws:
sns.heatmap(uniform_data,
cbar_kws={'format': '%.0f%%', 'ticks': [0, 100]},
vmax=100,
vmin=0)
You should get the colour bar object and then get the relevant axis object:
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
fig, ax = plt.subplots()
sns.heatmap(df, ax=ax, cbar_kws={'label': 'My Label'})
cbar = ax.collections[0].colorbar
cbar.ax.yaxis.set_major_formatter(PercentFormatter(1, 0))
You need to be able to access the colorbar object. It might be buried in the figure object somewhere, but I couldn't find it, so the easy thing to do is just to make it yourself:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, cbar=False, vmin=0, vmax=1)
cbar = ax.figure.colorbar(ax.collections[0])
cbar.set_ticks([0, 1])
cbar.set_ticklabels(["0%", "100%"])