I've successfully figured out how to display a matplotlib graph on a tkinter window. But, I want to have a button below the plot that will destroy it on command. Is there a way to accomplish this easily?
import tkinter as tk
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import datetime
from datetime import datetime as d
def clearplot():
figure.clf()
root= tk.Tk()
data = {'Input': hours,
'Output': [0,0,0,0,0,0,0,0,0,0,0,0]}
df = DataFrame(data,columns=['Input','Output'])
figure = plt.Figure(figsize=(3,2), dpi=100, facecolor='#f0f0f0')
ax = figure.add_subplot(111)
line = FigureCanvasTkAgg(figure, root)
line.get_tk_widget().pack()
df = df[['Input','Output']].groupby('Input').sum()
df.plot(kind='line', legend=False, ax=ax, color='black',marker='o', fontsize=10)
ax.set_title('Graph')
ax.xaxis.set_major_formatter(time_form)
figure.tight_layout()
clear_button=tk.Button(root,text="Clear",command=clearplot)
clear_button.pack()
root.mainloop()
Thanks.
Related
import pandas as pd
import tkinter
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sn
data= pd.read_csv(r'C:\Users\AmitSatappa\Desktop\praticalone\netflix_titles.csv',encoding='cp1252')
matplotlib.use('TkAgg')
duplicate= data[data.duplicated()]
data.drop_duplicates(inplace=True)
new_data= data[data.duplicated()]
nullvalue = data.isnull()
plt.ylim(1,3000)
sn.barplot(nullvalue)
plt.show()
[before setting the plt.ylim i was getting the graph but after setting the limit i am geeting it as blank onlyenter image description here](https://i.stack.imgur.com/mPHxz.png)
I'm trying to create a graph that displays plots two lines from live data. the values that will be displayed will come from two seperate encoders but for now I'm just using randrange to get data into the program. I've found some examples using matplotlib that I've modified, but once I try to add the second value it won't work
import itertools
from tkinter import *
from tkinter import ttk
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
x_len = 300
y_range = [0,300]
INTERVALS = 0
win = Tk()
# Set the window size
win.geometry("1024x600")
# --- Use TkAgg ---
matplotlib.use("TkAgg")
# Create a figure of specific size
figure = plt.figure(figsize=(11, 5), dpi=100)
gs = GridSpec(nrows=3, ncols=4)
#Create plot1
plot = figure.add_subplot(gs[:,0:3],)
xs = list(range(0, x_len))
ys = [0]* x_len
yc = [0]* x_len
plot.set_ylim(y_range)
line, = plot.plot(xs,ys)
def animate(i, ys,):
# get values
Pid = random.randrange(0,100)
sp = random.randrange(100,200)
# Add y to list
ys.append(Pid)
# Limit y list to set number of items
ys = ys[-x_len:]
# Update line with new Y values
line.set_ydata(ys)
return (line,)
ani = animation.FuncAnimation(figure,
animate,
fargs=(ys,),
interval=INTERVALS,
blit=True)
# Add a canvas widget to associate the figure with canvas
canvas = FigureCanvasTkAgg(figure, win)
canvas.get_tk_widget().grid(row=0, column=0)
win.mainloop()
Embedding Mapplotlib pie chart into Tkinter Gui help!
I am trying to embed a pie chart into my Tkinter window! So far I already have a frame in mind for the graph to be embedded in, frameChartsLT. This frame also already has a canvas, canvasChartsLT, placed over the entire area of the frame so I was hoping to place it on either of the of these but I keep getting the error.
AttributeError: 'tuple' object has no attribute 'set_canvas'
I checked my entire code but I can't even find anywhere where I wrote set_canvas so I am completely lost. Any help will be truly appreciated! I am also a beginner so the simpler the explanation or fix the better for me haha!
This is the portion of my code!
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# Some in-between code that sets the frame and canvas on my window
stockListExp = [ 'AMZN' , 'AAPL', 'JETS', 'CCL', 'NCLH']
stockSplitExp = [15,25,40,10,10]
plt.pie(stockSplitExp, radius=1, labels=stockListExp,autopct='%0.2f%%', shadow=True,) # 2 decimal points after plot
figChart1 = plt.pie(stockSplitExp, radius=1, labels=stockListExp,autopct='%0.2f%%', shadow=True)
plt.axis("equal")
chart1 = FigureCanvasTkAgg(figChart1,frameChartsLT)
chart1.get_tk_widget().place(x=10,y=10
You should use matplotlib.figure.Figure instead of pyplot when you combine tkinter with matplotlib. Below with modifications to your code:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
root = tk.Tk()
frameChartsLT = tk.Frame(root)
frameChartsLT.pack()
stockListExp = ['AMZN' , 'AAPL', 'JETS', 'CCL', 'NCLH']
stockSplitExp = [15,25,40,10,10]
fig = Figure() # create a figure object
ax = fig.add_subplot(111) # add an Axes to the figure
ax.pie(stockSplitExp, radius=1, labels=stockListExp,autopct='%0.2f%%', shadow=True,)
chart1 = FigureCanvasTkAgg(fig,frameChartsLT)
chart1.get_tk_widget().pack()
root.mainloop()
How can I change make the bar chart visible? i tried to change colors, however, It changes only bars, and the chart still looks blur as below:
import pandas as pd
df_train= pd.read_csv('/home/udas/scratch/imageclefdata/Training-Concepts.csv',sep=';',names=["filename", "class"])
import plotly.offline as py
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import gc
import matplotlib.pyplot as plt
import seaborn as sns
pal = sns.color_palette()
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import plotly.tools as tls
labels = df_train['class'].apply(lambda x: x.split(','))
from collections import Counter, defaultdict
counts = defaultdict(int)
for l in labels:
for l2 in l:
counts[l2] += 1
data=[go.Bar(x=list(counts.keys()), y=list(counts.values()))]
layout=dict(height=1200, width=800, title='Distribution of training labels')
fig=dict(data=data, layout=layout)
py.iplot(data, filename='train-label-dist')
how can I change the colors, and make this chart more transparent?
For some reason the y-tick and y-tick labels aren't showing up on my plot. The variable data is a pandas dataframe: rfr_scatter = pd.DataFrame({'Actual':y_test, 'Model Predicted':rfr_predictions})
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import tkinter as tk
from tkinter import *
def ScatterPlotter(notebooktab, data, test, pred):
f = Figure(figsize=(7,5), dpi=100)
ax1 = f.add_subplot(111, title="Model Performance")
for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label] +
ax1.get_xticklabels() + ax1.get_yticklabels()):
item.set_fontsize(8)
item.set_color('black')
markersize = 0.8
alpha = 0.05
line = np.arange(min(test), min(test) + 35, 5)
data.plot.scatter(x='Actual', y='Model Predicted', ax=ax1, s=markersize, alpha=alpha)
ax1.set_xlim((min(test),max(test)))
ax1.set_ylim((pred.min(),pred.max()))
ax1.plot(line,line,clr_red,'--', label = "Perfect")
canvas = FigureCanvasTkAgg(f, notebooktab)
canvas.show()
canvas.get_tk_widget().pack()
And i get this:
I have tried setting the yticks to visible, with no luck. I'm probably missing something simple...
EDIT: removing ax1.set_ylim((pred.min(),pred.max())) gives me a couple marks on the graph, it almost looks like the label is over the text, or the text isn't finishing rendering.
Changing ax1.plot(line,line,clr_red,'--', label = "Perfect") to ax1.plot(line,line,'r--', label = "Perfect") fixed the problem