Why does Matplotlib saved figure look weird? [duplicate] - python-3.x

This question already has answers here:
Matplotlib savefig background always transparent
(2 answers)
How to set opacity of background colour of graph with Matplotlib
(2 answers)
Closed 1 year ago.
I am using the plotting pandas data frame and, saved the resulting figure using the following code. The output file looks weird when opened in image viewer as shown here.I don't understand why the background is not fully white.
I am using Linux OS called Zorin, which is a derivative of Ubuntu if that makes a difference.
fig, ax = plt.subplots(figsize=(15, 10))
account_profit_df.plot(
style="*-",
figsize=(15, 10),
title="test",
ax=ax,
)
plt.grid()
fig.savefig(
image_path_backtest,
bbox_inches="tight",
)

This is the default behaviour, you can set the background color using: fig.patch.set_facecolor('white')

Related

Is it possible to update inline plots in Python (Spyder)?

Setup: Anaconda 3 (Win10 64), Spyder 4 and Python 3.7. The IPython Graphics setting is default (Inline).I'm still a new to Python but I've looked around and have not found an answer that solves my problem so far. Thanks everyone in advance.
So in this setup, whenever I create a plot using matplotlib, it appears in the plot pane of Spyder. e.g.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
bp = df.boxplot(column = 'A')
creates a boxplot. Now, if I want to add a title to the plot, the code would be
bp.set_title("This Title")
This is where I'm getting some problems. If I run the entire block together
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
bp = df.boxplot(column = 'A')
bp.set_title("This Title")
then I get a box plot with "This Title" as the title, showing up in the plot pane,
which is what I want.
However, if I run the above code line by line in the IPython console, the 2nd line will produce a boxplot as expected, but the 3rd line will not have an effect on the image in the plot pane, so the image in the plot pane still do not have a title
Now,if i go to Tools > Preference >IPython Console > Graphics and set the graphics backend to Automatic instead of the default Inline, then when I run the code in the Console line by line, I get an image that pops up in another window, and that it does update/refreshes based on new lines entered into the console. I understand that the inline plots are supposed to be static, but I thought I saw another post where someone said that it is possible to update inline plots? So now my questions are:
Do plots only update/refresh by line codes in the IPython console if the Graphics Backend is not static like inline?
Why do I get different result when I run code blocks vs line by line?
If it is possible to update the inline plots (preferably in the plot pane of Spyder), how do you do it? I've tried various methods to redraw the plots,for example
plt.show()
plt.draw()
bp.get_figure().canvas.draw()
but none of these updates the image in the plot pane. I figured that even if I can't update the image, I should at least be able to redraw it (i.e a 2nd image appears in the plot pane with the update characteristics). But nothing I've tried worked so far. Please advise and thanks again.
(Spyder maintainer here) About your questions:
Do plots only update/refresh by line codes in the IPython console if the Graphics Backend is not static like inline?
Correct.
Why do I get different result when I run code blocks vs line by line?
Because when you run code cells (which is what I think you mean by "code blocks") your plot is shown at the end of that code and hence it takes all modifications you've done to it in intermediate lines.
If it is possible to update the inline plots (preferably in the plot pane of Spyder), how do you do it?
No, it's not possible. As you correctly mentioned above, inline plots are static images, so they can't be modified.

How to fix OOP Issue with opacity change in pygame [duplicate]

This question already has answers here:
How to convert the background color of image to match the color of Pygame window?
(1 answer)
How do I make the screen ignore the background color of some image?
(1 answer)
Pygame image transparency confusion
(1 answer)
Closed 1 year ago.
I'm trying to make pieces of what makes pygame into it's own separate classes/definitions. But when trying to set the opacity of an image, Instead of showing up as excepted, It starts from it's set opacity and lightens up until it reaches the maximum opacity possible.
I have tried to see if the opacity changes in the module that contains the game, and in the module that contains the classes. Yet they end up giving me the correct number that should be the number that is set for the opacity. And yes I have looked for anything that could possibly start adding up the opacity by mistake.
This is the piece of the code that i'm using to edit an image.
class PicEditor:
def scale(Pic,scaleX,scaleY):
Pic.blit = pygame.transform.scale(Pic.blit,(scaleX,scaleY))
def opacity(Pic,opc):
Pic.blit.set_alpha(opc)
print(opc) #attempt at figuring out the problem
And this is the code that i'm trying to run.
while not crashed:
display.gameLoopTop() #the usual game loop used ontop in pygame
PicEditor.opacity(templatePic,opacityTemplate) #the issue
PicEditor.scale(templatePic,displayX,displayY) #scaling an image (works fine)
templatePic.blitIMG() #bliting the image
display.gameLoopBottom() #the bottom of a game loop which includes the clock function and pygame display update
pygame.quit()
exit()
The expected results are that the image will change it's opacity by 50 (opacityTemplate = 50), then that the image will fit the size of the screen (displayX,displayY) and then that it is blited.
Everything runs perfectly, except that the opacity of the image goes from it's number given- 50, and adds another 50 until it reaches the maximum opacity possible without crashing.

image not loading in opencv2 [duplicate]

This question already has answers here:
openCV imshow not rendering image on screen
(3 answers)
Closed 6 years ago.
I am using opencv2 in python to load image using the numpy
import numpy as np
import cv2
img=cv2.imgread('C:\im.jpg',0)
cv2.imshow('image',img)
when I execute this code the image window pops up but it doesn't show any image and crashes up.
You lack the waitKey() function after imshow.

Changing all font sizes in Tkinter/Python3 [duplicate]

This question already has answers here:
How to modify the default font in Tkinter?
(2 answers)
Closed 7 years ago.
I would like to change the font size globally in a Python3/Tkinter program. I've managed to do it in the buttons and labels in the main window, but I also have a messagebox in the program that only displays the default font size.
Im not certain but I believe you can use ttk to change global font size

Matplotlib Crash When Figure 1 not Closed Last

I am plotting mutliple figures using Matplotlib using Python 3.4.
When the multiple figures are open and I close the windows closing the first figure last (ie once all other figures are closed) python does not crash.
If, however, I close the first figure that was plotted first and then close the rest Python crashes.
It seems as though you need to close the windows in such an order that the first window that was opened must be closed last. Has anyone else experienced and is there a solution?
Here is a trivial example code that can be used to verify:
import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.plot([1,2,3])
plt.figure(2) # a second figure
plt.plot([4,5,6])
plt.show()
As discussed on the IPython bug tracker this is a bug in a TCL/TK library which is shipped with python 3.4 on windows.
Changing the backend to Qt works around the problem by using a different gui framework.
The way I have managed to solve this issue has been to use Qt4 as the matplotlib backend.
Simply add the following two lines of code after importing matplotlib.
import matplotlib as mpl
mpl.rcParams['backend'] = "qt4agg"
mpl.rcParams['backend.qt4'] = "PySide"
This is what I do on Python 3 and have no plot closing errors
I use this to do effectively what should be done by plt.close('all'):
def closeall(): # this closes all figures in reverse order
l = plt.get_fignums()
l.reverse()
for a in l:
plt.close(a)
Whenever you are plotting multiple figures, do not use plt.show, create your figures separately in a figure instance and add an Axes using add_subplot. Here is an example:
import matplotlib.pyplot as plt
fig1 = plt.figure()
ax1 = fig1.add_subplot(211) # the first subplot in the first figure
ax1.plot([1,2,3])
ax2 = fig1.add_subplot(212) # the second subplot in the first figure
ax2.plot([4,5,6])
plt.suptitle('Easy as 1,2,3')
fig1.show()
fig2 = plt.figure()
ax3 = fig2.add_subplot(211) # the first subplot in the second figure
ax3.plot([4,5,6])
ax4 = fig2.add_subplot(212) # the second subplot in the second figure
ax4.plot([4,5,6])
plt.suptitle('Easy as 1,2,3')
fig2.show()
By doing so you can still use your python shell even when the plots are active. This is the best way to plot multiple plots.

Resources