Hide Legend and Scale information on surface plot using pandas, plotly - python-3.x

I am at my wits end but so far did not find any documentation to solve my specific issue. I am using jupyter notebook.
I have two data frames, df1 & df2.
# libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import cufflinks as cf
cf.go_offline()
import plotly.graph_objs as go
# df1 & df2
np.random.seed(0)
dates = pd.date_range('20130101',periods=6)
df1 = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
df2 = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
I have two surface plots:
layout = go.Layout(
title='Random Numbers',
autosize=False,
width=500,
height=500,
margin=dict(
l=65,
r=50,
b=65,
t=90
)
)
df1.iplot(kind="surface", layout=layout)
df2.iplot(kind="surface", layout=layout)
I have three problems:
I need to plot them side by side as in (row = 1 & column = 2).
The scale legend is either removed or is shared.
The x and y in the axes are removed. I do not need to change them, just get rid of these.
Any help will be appreciated.

I'm sorry if this doesn't answer your question directly but I would suggest using plotly without cufflings.
import plotly
# Define scene which changes the default attributes of the chart
scene = dict(
xaxis=dict(title=''),
yaxis=dict(title=''),
zaxis=dict(title='')
)
# Create 2 empty subplots
fig = plotly.tools.make_subplots(rows=1, cols=2,
specs=[[{'is_3d': True}, {'is_3d': True}]])
# Add df1
fig.append_trace(dict(type='surface', x=df1.index, y=df1.columns, z=df1.as_matrix(),
colorscale='Viridis', scene='scene1', showscale=False), 1, 1)
# Add df2
fig.append_trace(dict(type='surface', x=df2.index, y=df2.columns, z=df2.as_matrix(),
colorscale='RdBu', scene='scene2', showscale=False), 1, 2)
# Set layout and change defaults with scene
fig['layout'].update(title='Random Numbers', height=400, width=800)
fig['layout']['scene1'].update(scene)
fig['layout']['scene2'].update(scene)
# Use plotly offline to display the graph
plotly.offline.plot(fig)
Output:
EDIT:
To answer your third question, you can use .update(scene) to change the axis attributes. Details are in the code above.

Related

How to create a line plot in python, by importing data from excel and using it to create a plot that shares a common X-Axis?

Trying to create a plot using Python Spyder. I have sample data in excel which I am able to import into Spyder, I want one column ('Frequency') to be the X axis, and the rest of the columns ('C1,C2,C3,C4') to be plotted on the Y axis. How do I do this? This is the data in excel and how the plot looks in excel (https://i.stack.imgur.com/eRug5.png) , the plot and data
This is what I have so far . These commands below (Also seen in the image) give an empty plot.
data = data.head()
#data.plot(kind='line', x='Frequency', y=['C1','C2','C3','C4'])
df = pd.DataFrame(data, columns=["Frequency","C1", "C2","C3","C4"])
df.plot(x = "Frequency",y=["C1", "C2","C3","C4"])
Here is an example, you can change columns names:
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({'X_Axis':[1,3,5,7,10,20],
'col_2':[.4,.5,.4,.5,.5,.4],
'col_3':[.7,.8,.9,.4,.2,.3],
'col_4':[.1,.3,.5,.7,.1,.0],
'col_5':[.5,.3,.6,.9,.2,.4]})
dfm = df.melt('X_Axis', var_name='cols', value_name='vals')
g = sns.catplot(x="X_Axis", y="vals", hue='cols', data=dfm, kind='point')
import pandas as pd
import matplotlib.pyplot as plt
path = r"C:\Users\Alisha.Walia\Desktop\Alisha\SAMPLE.xlsx"
data = pd.read_excel(path)
#df = pd.DataFrame.from_dict(data)
#print(df)
#prints out data from excl in tabular format
dict1 = (data.to_dict()) #print(dict1)
Frequency=data["Frequency "].to_list() #print (Frequency)
C1=data["C1"].to_list() #print(C1)
C2=data["C2"].to_list() #print(C2)
C3=data["C3"].to_list() #print(C3)
C4=data["C4"].to_list() #print(C4)
plt.plot(Frequency,C1)
plt.plot(Frequency,C2)
plt.plot(Frequency,C3)
plt.plot(Frequency,C4)
plt.style.use('ggplot')
plt.title('SAMPLE')
plt.xlabel('Frequency 20Hz-200MHz')
plt.ylabel('Capacitance pF')
plt.xlim(5, 500)
plt.ylim(-20,20)
plt.legend()
plt.show()

How to add two consequetive colors to bars in a plotly barchart with values of one pandas column

I would like to have a barchart where two colors are used for the bars, f.i. first blue next red, than blue again followed by red.
In matplotlib this is possible see below code.
I would like to do this also with plotly express.
Suggestions are appreciated.
df_1 = pd.DataFrame(freqfinal, columns=['teller' , 'frequenties']) # df = dataframe, pd staat voor Pandas
fig = go.Figure()
fig.add_trace(go.Bar(x=df_1.teller, y=df_1.frequenties, showlegend= True))
fig.show()
# in matplotlib, it works with two colors
bar_colors = ['red', 'blue']
ax = df_1['frequenties'].plot(kind='bar', color=bar_colors, title= 'series per 100 trekkingen') # barchart met behulp van matplotlib
ax.set_xlabel('volgorde frequenties') #label x-as
ax.set_ylabel('serie grootte') # label y-as
plt.show()
See above, first part is the plotly base code second part is the matplotlib code where I was succesful to have the two colors side by side
If you give us a list of desired color combinations for the marker color, we can create the expected color scheme.
import pandas as pd
import numpy as np
np.random.seed(1)
df_1 = pd.DataFrame({'teller': list('ABCDEFGHIK'), 'frequenties': np.random.randint(0,50,10)})
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=df_1.teller, y=df_1.frequenties, marker_color=['blue','red']*5, showlegend=True))
fig.show()

Plotly python facetted heatmaps

I'm using the example from this SO Q&A to use seaborn for facetted heatmaps in python. The result looks like this:
I'd like to do the same thing with plotly express and have tried with this starter code:
import plotly.express as px
df = px.data.medals_wide(indexed=True)
fig = px.imshow(df)
fig.show()
My data is also in a pd.DataFrame and it's important I show the groups the heatmaps are grouped by as well as the x/y-axis of the maps.
How do you extend the px.imshow example to create a facetted heatmap by group like the seaborn example above?
The sample data is taken from the referenced responses to answer the question. express, as data, can be subplotted if it is column data, but the results cannot be used with a categorical variable as the extraction condition with a different categorical variable, as in the sample data. You can draw it if it is as a subplot using a graph object in A heat map can be created by specifying the xy-axis in the data frame of the result of data extraction by category variable.
import numpy as np
import pandas as pd
import plotly.express
# Generate a set of sample data
np.random.seed(0)
indices = pd.MultiIndex.from_product((range(5), range(5), range(5)), names=('label0', 'label1', 'label2'))
data = pd.DataFrame(np.random.uniform(0, 100, size=len(indices)), index=indices, columns=('value',)).reset_index()
import plotly.graph_objects as go
from plotly.subplots import make_subplots
titles = ['label0='+ str(x) for x in range(5)]
fig = make_subplots(rows=1, cols=len(data['label0'].unique()),
shared_yaxes=True,
subplot_titles = tuple(titles))
for i in data['label0'].unique():
df = data[data['label0'] == i]
fig.add_trace(go.Heatmap(z=df.value, x=df.label1, y=df.label2), row=1, col=i+1)
fig.update_traces(showscale=False)
fig.update_xaxes(dtick=[0,1,2,3,4])
fig.update_xaxes(title_text='label1', row=1, col=i+1)
fig.update_yaxes(title_text='label2', row=1, col=1)
fig.show()

Facets not working properly plotly express

import plotly.graph_objects as go
import plotly.express as px
fig = px.histogram(df, nbins = 5, x = "numerical_col", color = "cat_1", animation_frame="date",
range_x=["10000","500000"], facet_col="cat_2")
fig.update_layout(
margin=dict(l=25, r=25, t=20, b=20))
fig.show()
How can I fix the output? I would like multiple subplots based on cat_2 where the hue is cat_1.
you have not provided sample data, so I've simulated it based on code you are using to generate figure
I have encountered one issue range_x does not work, it impacts y-axis as well. Otherwise approach fully works.
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
import pandas as pd
# data not provided.... simulate some
DAYS = 5
ROWS = DAYS * 2000
df = pd.DataFrame(
{
"date_d": np.repeat(pd.date_range("1-Jan-2021", periods=DAYS), ROWS // DAYS),
"numerical_col": np.random.uniform(10000, 500000, ROWS),
"cat_1": np.random.choice(list("ABCD"), ROWS),
"cat_2": np.random.choice(list("UVWXYZ"), ROWS),
}
)
# animation frame has to be a string not a date...
df["date"] = df["date_d"].dt.strftime("%Y-%b-%d")
# always best to provide pre-sorted data to plotly
df = df.sort_values(["date", "cat_1", "cat_2"])
fig = px.histogram(
df,
nbins=5,
x="numerical_col",
color="cat_1",
animation_frame="date",
# range_x=[10000, 500000],
facet_col="cat_2",
)
fig.update_layout(margin=dict(l=25, r=25, t=20, b=20))

X and Y label being cut in matplotlib plots

I have this code:
import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
start = datetime.date(2016,1,1)
end = datetime.date.today()
stock = 'fb'
fig = plt.figure(dpi=1400)
data = web.DataReader(stock, 'yahoo', start, end)
fig, ax = plt.subplots(dpi=720)
data['vol_pct'] = data['Volume'].pct_change()
data.plot(y='vol_pct', ax = plt.gca(), title = 'this is the title \n second line')
ax.set(xlabel="Date")
ax.legend(loc='upper center', bbox_to_anchor=(0.32, -0.22), shadow=True, ncol=2)
plt.savefig('Test')
This is an example of another code but the problem is the same:
At bottom of the plot you can see that the legend is being cut out. In another plot of a different code which i am working on, even the ylabel is also cut when i save the plot using plt.savefig('Test').How can i can fix this?
It's a long-standing issue with .savefig() that it doesn't check legend and axis locations before setting bounds. As a rule, I solve this with the bbox_inches argument:
plt.savefig('Test', bbox_inches='tight')
This is similar to calling plt.tight_layout(), but takes all of the relevant artists into account, whereas tight_layout will often pull some objects into frame while cutting off new ones.
I have to tell pyplot to keep it tight more than half the time, so I'm not sure why this isn't the default behavior.
plt.subplots_adjust(bottom=0.4 ......)
I think this modification will satisfy you.
Or maybe you can relocate the legend to loc="upper left"
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html
please also checked this issue which raised 8 years ago..
Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Resources