from matplotlib.pyplot import *
list = [1,3,5,7,2,4,6,8,10]
plot(list)
With my code above, the code will graph with x-axis run from 0 to 8. What should I do if I want my x-axis run from another value? i.e. my x-axis run from 120-128?
You can just use the show() function to show the graph.
Your code should look something like this.
from matplotlib.pyplot import *
list = [1,3,5,7,2,4,6,8,10]
plot(list)
show()
And also, as mentioned in the comments by #BcK, don't use keywords or in-built function names as variable names, finally don't import * , this is not a good practice. You can update your whole program to this:
import matplotlib.pyplot as plt
var_list = [1,3,5,7,2,4,6,8,10] # don't use keywords or inbuilt function names as varible names
plt.plot(var_list)
plt.show() # this is to visualize the plot
Related
I am using a function from a library that does some calculations and makes a plot, directly uses plt.show() to show that plot but only returns numerical output.
I guess this is intended for interactive analysis, but I would like to save the plot within a script, but plt.savefig() only saves an empty file.
Example code:
import numpy as np
import matplotlib.pyplot as plt
def show_plot_but_return_only_values(a):
# do something complicated to input
b = a*3
# show some complicated plot
fig, ax = plt.subplots()
ax.plot(b)
plt.show()
# return new output
return b
b = show_plot_but_return_only_values(np.random.random(7))
# saves empty file
plt.savefig(res_path / 'test.png')
For simple functions I could copy the function from the source code of the library, but this is not always possible/feasible (e.g., references to many other functions).
How can I save this plot?
This question already has an answer here:
How to save candlestick chart in matplotlib finance
(1 answer)
Closed 1 year ago.
I'm new to matplotlib. I'm struggling to customise elements of my plot within the first .plot call. For example, ylabel works but xlabel doesn't. I was hoping I could separate the savefig command so that I could add/modify elements of the plot between the first .plot call and the savefig call (because all the examples I see online seem to create the plot and then modify elements separately, i.e. the line fplt.xlabel("Blah")
I notice that a lot of plot examples I found online (for line graphs and such) provide all x and y values separately, but I like the plot technique I've used as it automatically uses high, low, etc. to create candles.
So why does this code work:
fplt.plot(
dft,
type="candle",
style='charles',
addplot=extraPlot2,
ylabel=stock,
# xlabel="Blah", <= removed as doesn't work
figratio=(10, 6), volume=True,
savefig=dict(
fname=folder2,
bbox_inches="tight"
)
)
But this code doesn't (even with the hashes added):
fplt.plot(
dft,
type="candle",
style='charles',
addplot=extraPlot2,
ylabel=stock,
# xlabel="Blah", <= removed as doesn't work
figratio=(10, 6), volume=True,
)
# fplt.xlabel("Blah") <= would like to do this if I can get savefig to work
# fplt.xticks(rotation=45) <= i'd also like to do stuff like this
fplt.savefig(folder2)
I've tried making fplt.plot a variable and targeting that but with no luck.
Apologies for any poor terminology, I am very new to this.
EDIT: Imports added below for reference. And I realise why xlabel wasn't working now, as I see I was importing it.
import datetime as dt
from matplotlib.pyplot import bar, xlabel
from numpy import False_, NaN
import pandas as pd
from pandas_datareader import data as pdr
import yfinance as yf
from tkinter import EXCEPTION, Tk
from tkinter.filedialog import askopenfilename
import os
from pandas import ExcelWriter
import mplfinance as fplt
from pathlib import Path
You can import the Matplotlib pyplot module and use the gcf() ("get current figure") function to return a Figure object. It is the Figure object that has the savefig() method. E.g.,
from matplotlib import pyplot as plot
# your code here
fig = plt.gcf() # gcf is "get current figure"
fig.savefig(folder2)
Looking at this mplfinance issue it also looks like you can return the figure object with:
fig, axlist = fplt.plot(..., returnfig=True)
# save figure
fig.savefig(folder2)
I'm trying to create a grapher using matplotlib.pyplot and want to graph a function that comes like a string
My Code is:
import matplotlib.pyplot as mpl
import numpy as np
def plot2D(*args):
mpl.grid(1)
xAxis = np.arange(args[1],args[2],args[3])
def xfunction(x,input):
return eval(input)
print(xfunction(5,args[0]))
mpl.plot(xAxis,xfunction(xAxis,args[0]))
mpl.show()
plot2D("1/(x)",-1,2,0.1)
I want it to plot the function 1/x but it looks like this when it should look like this (desmos). Am I converting the string to a function wrong or can matplotlib even be used to graph functions like that or should I use another library? How would I go about graphing a function like x**2 + y**2 = 1 ? Or functions like sin(x!) ?
There's an intrinsic problem with the function 1/x: it's not defined in 0. Now, in your code one of the values inside the range is unfortunately 0, and thus it messes up the whole thing big time. All you have to do is change the last line of code to shift the range a little bit, and increase the number of steps in order to get more accurate results: plot2D("1/x",-1.01,2,0.02). This is the plot:
If you want to eliminate the nasty line in between you'll have to change the code to split the graph into two.
I often plot a point on a matplotlib plot with:
x = 10
y = 100
plot(x, y, "k*", label="Global Optimum")
legend()
However, this causes the legend to put a star in the legend twice, such that it looks like:
* * Global Optimum
when I really want it to look like:
* Global Optimum
How do I do this?
This should work:
legend(numpoints=1)
BTW, if you add the line
legend.numpoints : 1 # the number of points in the legend line
to your matplotlibrc file, then this will be the new default.
[See also scatterpoints, depending on your plot.]
API: Link to API docs
I like to change my matplotlib rc parameters dynamically in every python script. To achieve this goal I simply use somthing like that at the beginning of my python files.
from pylab import *
rcParams['legend.numpoints'] = 1
This will apply to all plots generated from my python file.
EDIT: For those who do not like to import pylab, the long answer is
import matplotlib as mpl
mpl.rcParams['legend.numpoints'] = 1
I have written a relatively simple function in python that can be used to plot the time domain history of a data set as well as the frequency domain response of a data set after a fast fourier transform. In this function I use the command from pylab import * to bring in all the necessary functionality. However, despite successfully creating the plot, I get a warning stating
import * only allowed at the module level.
So if using the command from pylab import * is not the preferred methodology, how do I properly load all the necessary functionality from pylab. The code is attached below. Also, is there a way to close the figure after the function is exited, I have tried plt.close() which is not recognized for subplots?
def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
# Directory: The path length to the directory where the output file is
# to be stored
# Title: The name of the output plot, which should end with .eps or .png
# X_Label: The X axis label
# Y_Label: The Y axis label
# X_Data: X axis data points (usually time at which Yaxis data was acquired
# Y_Data: Y axis data points, usually amplitude
from pylab import *
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
Output_Location = Directory.rstrip() + Title.rstrip()
fig,plt = plt.subplots()
matplotlib.rc('xtick',labelsize=18)
matplotlib.rc('ytick',labelsize=18)
plt.set_xlabel(X_Label,fontsize=18)
plt.set_ylabel(Y_Label,fontsize=18)
plt.plot(X_Data,Y_Data,color='red')
fig.savefig(Output_Location)
plt.clear()
From the matplotlib documentation:
pylab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and numpy (for mathematics and working with arrays) in a single name space. Although many examples use pylab, it is no longer recommended.
I would recommend not importing pylab at all, and instead try using
import matplotlib
import matplotlib.pyplot as plt
And then prefixing all of your pyplot functions with plt.
I also noticed that you assign the second return value from plt.subplots() to plt. You should rename that variable to something like fft_plot (for fast fourier transform) to avoid naming conflicts with pyplot.
With regards to your other question (about fig, save fig()) you're going to need to drop that first fig because it's not necessary, and you'll call savefig() with plt.savefig() because it is a function in the pyplot module. So that line will look like
plt.savefig(Output_Location)
Try something like this:
def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data):
# Directory: The path length to the directory where the output file is
# to be stored
# Title: The name of the output plot, which should end with .eps or .png
# X_Label: The X axis label
# Y_Label: The Y axis label
# X_Data: X axis data points (usually time at which Yaxis data was acquired
# Y_Data: Y axis data points, usually amplitude
import matplotlib
from matplotlib import rcParams, pyplot as plt
rcParams.update({'figure.autolayout': True})
Output_Location = Directory.rstrip() + Title.rstrip()
fig,fft_plot = plt.subplots()
matplotlib.rc('xtick',labelsize=18)
matplotlib.rc('ytick',labelsize=18)
fft_plot.set_xlabel(X_Label,fontsize=18)
fft_plot.set_ylabel(Y_Label,fontsize=18)
plt.plot(X_Data,Y_Data,color='red')
plt.savefig(Output_Location)
plt.close()