Bonjour,
"sparkline" does not work in my code.
Already, I didn't manage to install it. So, I found a function that I call "sparkline_test. Nevertheless, the images that should be integrated in the table are outside. Something is wrong.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from io import BytesIO
from itertools import islice
import seaborn as sns
import base64
I cannot import sparklines:
#import sparklines
df = sns.load_dataset('titanic')
def percentile_90(x):
return x.quantile(.9)
from scipy.stats import trim_mean
def trim_mean_10(x):
return trim_mean(x, 0.1)
def largest(x):
return x.nlargest(1)
def sparkline_str(x):
bins=np.histogram(x)[0]
sl = ''.join(sparklines(bins))
return sl
def sparkline_test(data, figsize=(4,0.25),**kwags):
data = list(data)
fig,ax = plt.subplots(1,1,figsize=figsize,**kwags)
ax.plot(data)
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
plt.plot(len(data)-1, data[len(data)-1], 'r.')
ax.fill_between(range(len(data)), data, len(data)*[min(data)], alpha=0.1)
img = BytesIO()
plt.savefig(img, transparent=True, bbox_inches='tight')
img.seek(0)
plt.show()
# plt.close()
return base64.b64encode(img.read()).decode("utf-8")
def sparkline_str(x):
bins=np.histogram(x)[0]
sl = ''.join(sparkline_test(bins))
return sl
agg_func_largest = {
'fare': [percentile_90, trim_mean_10, largest, sparkline_test]
#'fare': [percentile_90, trim_mean_10, largest]
}
df.groupby(['class', 'embark_town']).agg(agg_func_largest)
that produces:
What is expected is:
Something is wrong....But what?
Do you have any idea?
Regards,
Atapalou
Related
I have a sensor_msgs/PointCloud2 with [x,y,z] and how can I plot it in real-time in matplotlib like this code here. I already changed the type from Odometry to pointcloud2 but I don't know what to change in odom_callback or how to change the code in order to plot it in matplotlib. Can someone has an idea how to plot pointcloud2 in matplotlib
import matplotlib.pyplot as plt
import rospy
import tf
from sensor_msgs.msg import PointCloud2
from tf.transformations import quaternion_matrix
import numpy as np
from matplotlib.animation import FuncAnimation
class Visualiser:
def __init__(self):
self.fig, self.ax = plt.subplots()
self.ln, = plt.plot([], [], 'ro')
self.x_data, self.y_data = [] , []
def plot_init(self):
self.ax.set_xlim(0, 10000)
self.ax.set_ylim(-7, 7)
return self.ln
def getYaw(self, pose):
quaternion = (pose.orientation.x, pose.orientation.y, pose.orientation.z,
pose.orientation.w)
euler = tf.transformations.euler_from_quaternion(quaternion)
yaw = euler[2]
return yaw
def odom_callback(self, msg):
yaw_angle = self.getYaw(msg.pose.pose)
self.y_data.append(yaw_angle)
x_index = len(self.x_data)
self.x_data.append(x_index+1)
def update_plot(self, frame):
self.ln.set_data(self.x_data, self.y_data)
return self.ln
rospy.init_node('publisher_node')
vis = Visualiser()
sub = rospy.Subscriber('/scan3dd', PointCloud2, vis.odom_callback)
ani = FuncAnimation(vis.fig, vis.update_plot, init_func=vis.plot_init)
plt.show(block=True)
I am already having Tkinter(someone said to install a tkinter)
code used:
imports are:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
if u want to view the data-set then it is :
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv")
code used to plot boxplot in jupyter notebook
fig, ax = plt.subplots(figsize = (20,20))
sns.boxplot(data = df,ax = ax)
)
I was supposed to add in my import's
%matplotlib inline
Some plots are showing up partially drawn. Looks like there is some global state that needs to be locked on?
import matplotlib.pyplot as plt
import numpy as np
import dask
import os
from dask.distributed import Client
client = Client(processes=False)
def oneplot(x):
fig = plt.figure(num=f'{x}')
ax = fig.subplots(1, 1)
ax.plot(np.random.randn(100))
plt.savefig(os.path.expanduser(f'~/test_{x}.png'))
def test():
d = [client.submit(oneplot, i) for i in range(10)]
return d
I had the same issue when working with dask and matplotlib. I solved it using fig.savefig(...) instead of using plt.savefig(...). It might work for you as well.
import numpy as np
import os.path
from skimage.io import imread
from skimage import data_dir
img = imread(os.path.join(data_dir, 'checker_bilevel.png'))
import matplotlib.pyplot as plt
#plt.imshow(img, cmap='Blues')
#plt.show()
imgT = img.T
plt.figure(1)
plt.imshow(imgT,cmap='Greys')
#plt.show()
imgR = img.reshape(20,5)
plt.figure(2)
plt.imshow(imgR,cmap='Blues')
plt.show(1)
I read that plt.figure() will create or assign the image a new ID if not explicitly given one. So here, I have given the two figures, ID 1 & 2 respectively. Now I wish to see only one one of the image.
I tried plt.show(1) epecting ONLY the first image will be displayed but both of them are.
What should I write to get only one?
plt.clf() will clear the figure
import matplotlib.pyplot as plt
plt.plot(range(10), 'r')
plt.clf()
plt.plot(range(12), 'g--')
plt.show()
plt.show will show all the figures created. The argument you forces the figure to be shown in a non-blocking way. If you only want to show a particular figure you can write a wrapper function.
import matplotlib.pyplot as plt
figures = [plt.subplots() for i in range(5)]
def show(figNum, figures):
if plt.fignum_exists(figNum):
fig = [f[0] for f in figures if f[0].number == figNum][0]
fig.show()
else:
print('figure not found')
I am trying to plot a dataframe graph in tkinter , such that it is ploted in the window of the application.
My code is :
import tkinter as tk
from tkinter import ttk, Canvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pandas as pd
class application():
def __init__(self):
self.win = tk.Tk()
self.win.title('Emetor')
self.win.geometry('700x650+230+30')
self.win.configure(background='pale green')
self.createWidgets()
def createWidgets(self):
self.var1 = tk.IntVar()
self.check1 = tk.Checkbutton(self.win, text='1',command= self.mat, variable=self.var1)
self.check1.grid(row=1,column=0)
def mat(self):
data=[{'a':1,'b':2},{'a':1,'b':4},{'a':1,'b':6},{'a':1,'b':8}]
index=['1','2','3','4']
fig=Figure(figsize=(4,5), facecolor='white')
a=fig.add_subplot(111)
df = pd.DataFrame(data, index=index)
df.plot(kind='bar')
plt.show()
canvas=FigureCanvasTkAgg(fig, self.win)
canvas.get_tk_widget().grid(row=1, column=0, columnspan=4)
canvas.show()
if __name__ == '__main__':
app = application()
app.win.mainloop()
and the result is :
dataframe bar graph
If someone has any idea how to make the figure show in the main widow not in a seperated one, it would be a great help for me .
Thank you :)