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

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

Related

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

plotly candlestick in python with flag

I set up a candlestick chart using plotly and would like to know if you can create on top of that chart based on the flag column containing the number 1, a rectangle that overlaps candlesticks
Code:
import pandas as pd
import plotly.graph_objects as go
df = pd.DataFrame({"data_minu": ['30/10 09:00','30/10 09:05','30/10,09:10','30/10 09:15','30/10 09:20','30/10 09:25','30/10 09:30','30/10 09:35','30/10 09:40','30/10 09:45'],
"Open":['10','17','23','20','8','22','24','25','29','22'],
"High":['21','27','25','29','24','27','28','32','29','25'],
"Low":['6','12','18','9','5','8','24','18','15','10'],
"Close":['17','24','22','10','21','25','26','30','18','10'],
"Flag": ['0','1','1','1','0','1','1','1','0','0']})
fig = go.Figure(data=[go.Candlestick(x=df['data_minu'],
open=df['Open'], high=df['High'],
low=df['Low'], close=df['Close'])
])
fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()
Current result:
Outline for desired result:
. The people on the plotly website helped me with this question. I share their answer and on top of it to make various adjustments.
https://community.plot.ly/t/plotly-candlestick-in-python-with-flag/31154
Thanks .

Change the colors of outline and median lines of boxplot in matplotlib

I am trying to create boxplot from pandas dataframe using matplotlib.
I am able to get the boxplot and change the linewidth of outlines and median lines, but I would like to change all the colors to black.
I tried several ways as described in Pandas boxplot: set color and properties for box, median, mean and Change the facecolor of boxplot in pandas.
However, none of them worked for my case.
Could someone solve these problems?
Here are my codes:
version: python 3.6.5
import pandas as pd
from pandas import DataFrame, Series
import matplotlib.pyplot as plt
df = pd.read_excel("training.xls")
fig = plt.figure()
ax = fig.add_subplot(111)
boxprops = dict(color="black",linewidth=1.5)
medianprops = dict(color="black",linewidth=1.5)
df.boxplot(column=["MEAN"],by="SrcID_Feat",ax=ax,
boxprops=boxprops,medianprops=medianprops)
plt.grid(False)
Result
I found that unless I add the argument patch_artist=True, none of the boxprops dictionaries have any effect on the boxplot. For example, when I generated a boxplot where I changed the facecolor to yellow, I had to use the following coding:
plt.boxplot(boxplot_data, positions=[1], patch_artist=True, boxprops=dict(facecolor='yellow'), showmeans=True)
Here is a way to solve your problem (details which are not relevant for the question are omitted):
fig, ax = plt.subplots()
box_plot = ax.boxplot(..., patch_artist=True)
for median in box_plot['medians']:
median.set_color('black')
median is an object of type matplotlib.lines.Line2D which exposes a method set_color which can be used to set the color of each box.

Plotting Pandas into subplots

da is my dataframe. I want to make this figure into one subplot out of 2 that I will have. When I add plt.subplots(2,1,2) for this figure it ends up separating this figure into a separate figure and the subplot is an empty figure.
How can I make this code into a subplot?
-Thank you in advance, I am a newbie in python.
ax1 = da.plot(rot = 90, title ='Pre-Folsom Dam Spring Recession')
ax1.set_xlabel('Water Year Day')
ax1.axhline( y = float(fSP_Mag) , xmin=0, xmax=35,color ='r', linestyle='--',zorder=0,label= 'Magnitude')
ax1.axvline(x=float(fSP_Tim), color ='r',linestyle='--', label='Timing')
ax1.legend(framealpha=1, frameon=True)
import pandas as pd
import matplotlib.pyplot as plt
data=pd.DataFrame({"col1":[1,2,3,4,5],"col2":[2,4,6,8,10]})
fig=plt.figure()
ax1=fig.add_subplot(2,1,1)
ax2=fig.add_subplot(2,1,2)
data["col1"].plot(ax=ax1)
data["col2"].plot(ax=ax2)
Create a plt.figure() and assign subplots to ax1 and ax2.Now plot the dataframe using these axes.
Reference:-
Pyplot

Hide Legend and Scale information on surface plot using pandas, plotly

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.

Resources