I am not using subplots for this since the requirement is of legend beside the chart which is not possible by using subplots. Subplots only lets the legend at once place, hence I have thought of using to different plots and placing them beside each other.
Here is the code which produced two charts, but i am unable to place them beside each other.
fig = go.Figure()
fig.add_trace(go.Scatter(x=data['time'],y=data['x'],mode='lines',name='xyz',hoverlabel=dict(bgcolor=['white']),hovertemplate='abcd<br>Probability: %{y}'))
fig.add_trace(go.Scatter(x=data['time'],y=predict_data['y'],mode='lines',name='abc'))
fig.update_layout(title='TRend charts',yaxis_title='Probabilities',autosize=False,width=1000,height=600,margin=dict(l=50,r=50,b=100,t=100,pad=4),paper_bgcolor='lightpink',xaxis_showgrid=False)
p_8 = opy.plot(fig,auto_open=False,output_type='div')
fig = go.Figure()
fig.add_trace(go.Scatter(x=data['time'],y=data['xy'],mode='lines',name='xyz1'))
fig.add_trace(go.Scatter(x=data['time'],y=data['ab'],mode='lines',name='abc`'))
fig.update_layout(title='Second Chart',yaxis_title='Probabilities',autosize=False,width=100,height=600,margin=dict(l=50,r=-50,b=100,t=100,pad=3),paper_bgcolor='yellow',xaxis_showgrid=False)
p_9 = opy.plot(fig,auto_open=False,output_type='div')
I get them one below the other. Any attributes which can get them beside each other?
Try this
fig = fig.make_subplots(rows=2, cols=1)
Related
Im trying to plot a bar plot in plotly that is representing net-gains (will have positive and negative bar values). But somewhat the negative values in the y-axis are being represented in gibberish. I tried several things, including using update_layout function, but nothing seems to work. Im using the make_subplots function because i want to plot multiple viz on one figure.
Im using databricks for this code.
Attaching my code and viz output:
net_gains = pd.DataFrame()
net_gains["general_net_gain"] = [-2,2,-1,2]
fig = plotly.subplots.make_subplots(rows=1, cols=1)
fig.add_bar(x=net_gains.index, y=net_gains["general_net_gain"], row=1, col=1)
fig.update_layout(height=400,width=500,showlegend=True)
I have a collection of charts I need to put on the same pdf, but they are grouped into different subplot grids like below.
Ex. I have something like
fig, axes = plt.subplots(num_rows, num_cols)
fig2, axes2 = plt.subplots(num_rows2, num_cols2)
fig3, axes3 = plt.subplots(num_rows3, num_cols3)
# more figures
I'm trying a find a way of arranging the figures in the the pdf in a custom way, similar to what you can do with subplots,
fig, axis = plt.subplots(rows, cols)
axis[0, 0].plot(X, Y)
axis[0, 1].plot(X2, Y2)
but instead of a grid of axises it would be a grid of figures, and I could tell matplotlib which row or column each figure goes in.
Is there a way to do this? One workaround is to just have one figure and calculate the positions of all the plots manually based on which group there are in, but I'm wondering if there's something built in to matplotlib to do this.
I am trying to create a waterfall chart, which is like a bar chart, except that each bar starts at the end of its neighboring bars, at the end or beginning, so you have the total, and can see how it breaks down.
I am trying to create this chart in python, but there are no direct charts in matplot.lib called waterfall.
I found code for a vertical waterfall, but I could not transform it to horizontal.
How can I transform a barh matplot chart, for example, to a horizontal waterfall?
I want to create a HORIZONTAL waterfall.
For example, I am trying to make each bar in barh chart in matplotlib start at end of other, but I do not think I am approaching the problem the right way, because I have no results so far.
It should look like this:
Code to create the plot:
my_plot = trans.plot(
kind='barh',
stacked=True,
bottom=blank,legend=None,
figsize=(10, 5)
)
How do I separate the bars?
EDIT
I have found this ready to use python package, but it doesn't work with dataframes, so I cannot use it.
import waterfall_chart
from matplotlib import transforms
a = ['sales','returns','credit fees','rebates','late charges','shipping']
b = [10,-30,-7.5,-25,95,-7]
my_plot = waterfall_chart.plot(a, b, rotation_value=30, sorted_value=True, threshold=0.2,
formatting="$ {:,.1f}", net_label="end result", other_label="misc",
Title="chart", x_lab="X", y_lab="money", blue_color="blue",
green_color="#95ff24", red_color="r")
rot = transforms.Affine2D().rotate_deg(90)
my_plot.show()
I also found this tutorial, with code, for a vertical waterfall chart.
https://pbpython.com/waterfall-chart.html.
It works great, but I didn't manage to reproduce the same thing for a horizontal waterfall.
I'm very new to Python, and I want to plot 13 different figures all in one plot. To do this nicely, I would like to plot the first 12 figures in a 6x2 grid (this works just fine), and then plot the 13th figure below it; either the same size as the other figures and centered, or larger than the rest so that its width is equal to twice the width of the other figures and all the edges are aligned. What would be the best way to specify axes of this kind using subplots? (So far, I've just used nrows=6, ncols=2, but I think something like that won't work with an odd number of figures to plot.) The code I have so far for plotting the first 12 plots looks like this (with simple test data):
fig, axes = plt.subplots(nrows=6, ncols=2, figsize=(45,10))
for ax in axes.flat:
ax.plot([1,2,3,4])
fig.subplots_adjust(right=0.5)
How can I add a 13th figure below the others?
You can use GridSpec (link to documentation) to generate flexible axes layout.
The following code creates the desired layout and puts all Axes objects in a list for easy access.
gs00 = matplotlib.gridspec.GridSpec(7, 2)
fig = plt.figure()
axs = []
for i in range(6):
for j in range(2):
ax = fig.add_subplot(gs00[i,j])
axs.append(ax)
ax = fig.add_subplot(gs00[6,:])
axs.append(ax)
I have a function that plots a graph. I can call this graph with different variables to alter the graph. I'd like to call this function multiple times and plot the graphs along side each other but not sure how to do so
def plt_graph(x, graph_title, horiz_label):
df[x].plot(kind='barh')
plt.title(graph_title)
plt.ylabel("")
plt.xlabel(horiz_label)
plt_graph('gross','Total value','Gross (in millions)')
In case you know the number of plots you want to produce beforehands, you can first create as many subplots as you need
fig, axes = plt.subplots(nrows=1, ncols=5)
(in this case 5) and then provide the axes to the function
def plt_graph(x, graph_title, horiz_label, ax):
df[x].plot(kind='barh', ax=ax)
Finally, call every plot like this
plt_graph("framekey", "Some title", "some label", axes[4])
(where 4 stands for the fifth and last plot)
I have created a tool to do this really easily. I use it all the time in jupyter notebooks and find it so much neater than a big column of charts. Copy the Gridplot class from this file:
https://github.com/simonm3/analysis/blob/master/analysis/plot.py
Usage:
gridplot = Gridplot()
plt.plot(x)
plt.plot(y)
It shows each new plot in a grid with 4 plots to a row. You can change the size of the charts or the number per row. It works for plt.plot, plt.bar, plt.hist and plt.scatter. However it does require you use matplot directly rather than pandas.
If you want to turn it off:
gridplot.off()
If you want to reset the grid to position 1:
gridplot.on()
Here is a way that you can do it. First you create the figure which will contain the axes object. With those axes you have something like a canvas, which is where every graph will be drawn.
fig, ax = plt.subplots(1,2)
Here I have created one figure with two axes. This is a one row and two columns figure. If you inspect the ax variable you will see two objects. This is what we'll use for all the plotting. Now, going back to the function, let's start with a simple dataset and define the function.
df = pd.DataFrame({"a": np.random.random(10), "b": np.random.random(10)})
def plt_graph(x, graph_title, horiz_label, ax):
df[x].plot(kind = 'barh', ax = ax)
ax.set_xlabel(horiz_label)
ax.set_title(graph_title)
Then, to call the function you will simply do this:
plt_graph("a", "a", "a", ax=ax[0])
plt_graph("b", "b", "b", ax=ax[1])
Note that you pass each graph that you want to create to any of the axes you have. In this case, as you have two, you pass the first to the first axes and so on. Note that if you include seaborn in your import (import seaborn as sns), automatically the seaborn style will be applied to your graphs.
This is how your graphs will look like.
When you are creating plotting functions, you want to look at matplotlib's object oriented interface.