Matplotlib y-tick labels not showing - python

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

Related

i am getting blank chart after setting plt.ylim

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)

Creating two lines with live data using matplotlib and tkinter

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()

Is there a way to destroy a matplotlib figure live in tkinter?

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.

How to set matplotlib to show every image of an array?

How to set matplotlib to show every image of an array?
I want that everytime i click on the right arrow, it shows the next image and so on...
Is that possible?
width = 14
height = 14
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
data_images = X_train.reshape(X_train.shape[0],width,height)
print "Shape " ,data_images.shape #Shape (50000L, 14L, 14L)
plt.imshow(data_images[0])
plt.show()
I wanted to pass the "data_images" variable to plt.imshow and so everytime i clicked on next on the matplotlib, it would show the next image.
Working example with plt.connect().
You can change image by pressing any key.
import matplotlib.pyplot as plt
data_images = [
[[1,2,3],[1,2,3],[1,2,3]],
[[1,1,1],[2,2,2],[3,3,3]],
[[1,2,1],[2,2,2],[1,2,1]],
]
#----------------------------------
index = 0
def toggle_images(event):
global index
index += 1
if index < len(data_images):
plt.imshow(data_images[index])
plt.draw()
else:
plt.close()
#----------------------------------
plt.imshow(data_images[index])
plt.connect('key_press_event', toggle_images)
plt.show()
I would do this using ipywidgets within the IPython notebook. Here's an example:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact
images = np.random.random((500, 14, 14))
def browse_images(images):
N = images.shape[0]
def view_image(i=0):
plt.imshow(images[i], cmap='gray', interpolation='nearest')
plt.title('Image {0}'.format(i))
interact(view_image, i=(0, N-1))
browse_images(images)
Edit: the result, in the notebook page, will look something like this:
You can press the left or right arrow to advance the slider and view the next image.
You can do a bit better in the notebook than using inline:
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact
from IPython.display import display
images = np.random.random((500, 14, 14))
fig, ax = plt.subplots()
im = ax.imshow(images[0], cmap='gray', interpolation='nearest')
def browse_images(images):
N = images.shape[0]
def view_image(i=0):
im.set_data(images[i])
ax.set_title('Image {0}'.format(i))
fig.canvas.draw_idle()
interact(view_image, i=(0, N-1))
and then in the next cell
browse_images(images)
which will give you a pannable/zoom able figure. In mpl 1.5.0 you also get the pixel values under the cursor by default.
(I tested this on tmpnb.org)

Multiple matplotlib plots in reportlab

I'm trying to put a matplotlib graph onto a reportlab canvas. I can do a simple graph with the code from this question: How to drawImage a matplotlib figure in a reportlab canvas?
But when I try to use subplots or use multiple plots it will not work properly. Doing it this way causes the same image to be plotted twice even when I added things like imgdata.close() or deleting the figure:
from matplotlib.figure import Figure
import cStringIO
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
can = canvas.Canvas()
self.f = Figure()
plot(x,y)
xlabel(xlbl)
ylabel(ylbl)
imgdata=cStringIO.StringIO()
savefig(imgdata,format='png')
imgdata.seek(0)
Image = ImageReader(imgdata)
can.drawImage(Image,100,250, width=400,height=350)
self.g = Figure()
plot(x,y)
xlabel(xlbl)
ylabel(ylbl)
secondimgdata = cStringIO.StringIO()
savefig(secondimgdata,format='png')
secondimgdata.seek(0)
Image2 = ImageReader(secondimgdata)
can.drawImage(Image2,100,150, width=400,height=350)
When trying with subplots it simply produces a blank graph and I did not know where to go with it:
self.f = Figure()
self.a = self.f.add_subplot(111)
self.a.plot(x,y)
self.a2 =self.a.twinx()
self.a2.plot(x,y2,'r')
self.a2.set_ylabel(ylbl2)
self.a.set_xlabel(xlbl)
self.a.set_ylabel(ylbl)
Any solution or advice to this problem would be very much appreciated.
The key is that you must use plt.close() after you're done adding images. Here's a quick example that works for me using seaborn and barplot. Assume I have a dataframe with different data that I want plotted over a few figures.
import matplotlib.pyplot as plt
import seaborn as sns
import cStringIO
from reportlab.platypus import Image
my_df = <some dataframe>
cols_to_plot = <[specific columns to plot]>
plots = []
def create_barplot(col):
sns_plot = sns.barplot(x='col1', y=col, hue='col2', data=my_df)
imgdata = cStringIO.StringIO()
sns_plot.figure.savefig(imgdata, format='png')
imgdata.seek(0)
plots.append(Image(imgdata))
plt.close() # This is the key!!!
for col in cols_to_plot:
create_barplot(col)
for barplot in plots:
story.append(barplot)
This isn't an ideal solution as it has to save the file as an image instead of using StringIO but it works.
import Image as image
from matplotlib.pyplot import figure
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
can = canvas.Canvas()
self.f = figure()
self.a = self.f.add_subplot(2,1,1)
self.a.plot(x,y)
self.a2 =self.a.twinx()
self.a2.plot(x,y2,'r')
self.a2.set_ylabel(ylbl2,color='r')
self.a.set_xlabel(xlbl)
self.a.set_ylabel(ylbl,color='b')
self.f.savefig('plot.png',format='png')
image.open('plot.png').save('plot.png','PNG')
can.drawImage('plot.png',100,250, width=400,height=350)

Categories