This question already has answers here:
How to show all x-axis tick values in Plotly?
(3 answers)
Closed 4 months ago.
I need to change the x-axis of this chart. The dataframe has time data per day, from 2012 to October 2022. I want to be able to see in the xaxis all the years and the chart shows me only every 2 years.
import plotly.express as px
fig = px.line(data_SPY, y=['Close'], line_shape='linear', color_discrete_sequence=["#930435"],
labels={'value': "Precio", 'Date': "Fecha"})
fig.update_layout(
showlegend=False,
title= 'Precio SPY ETF',
font_color= "#000000",
font_family="Tahoma",
xaxis = dict(
tickangle = 0,
ticklabelstep=1,
showgrid=True,
),
yaxis = dict(
showgrid=True
),
legend = dict(
orientation='v'
),
paper_bgcolor='#FFFFFF'
)
fig.show(renderer="iframe")
enter image description here
You'd need to specify the dtick.
fig.update_xaxes(dtick='Y1')
Related
This question already has answers here:
X-axis not properly aligned with bars in barplot (seaborn)
(2 answers)
Bar labels in matplotlib/Seaborn
(1 answer)
How to get the label values on a bar chat with seaborn on a categorical data
(2 answers)
Closed 2 months ago.
The code below is the code I am using for a heart failure analysis project. But,
This method is not centering the values of each bar under the graph, pictured below.
I am not getting the percentage value above each bar in the graph
def plot_percentage(df, col, target):
x,y = col, target
temp_df = df.groupby(x)[y].value_counts(normalize=True)
temp_df = temp_df.mul(100).rename('percent').reset_index()
temp_df = temp_df[temp_df.HeartDisease != 0]
order_list = list(df[col].unique())
order_list.sort()
sns.set(font_scale=1.5)
g = sns.catplot(x=x, y='percent', hue=x,kind='bar', data=temp_df, height=8, aspect=2, order=order_list, legend_out=False)
g.ax.set_ylim(0,100)
plt.title(f'{col.title()} By Percent {target.title()}',
fontdict={'fontsize': 30})
plt.xlabel(f'{col.title()}', fontdict={'fontsize': 20})
plt.ylabel(f'{target.title()} Percentage', fontdict={'fontsize': 20})
return g
I'm pretty new using plotly in python. I managed to plot a box chart with my dataframe in plotly like this:
box chart
The box plot shows the entire department's performance. I wish to add a few buttons that filter or narrow down the result. For example:
Team 1 button - filter on JH, DT, MB, SC
Team 2 button - filter on NP, DH, MZ, SB
Team 3 button - filter on KT, BL, SM,LW
and so on
I read through the plotly Figure reference (https://plotly.com/python/reference/layout/updatemenus/#layout-updatemenus-items-updatemenu-buttons-items-button-args)
and managed to add the buttons with args=["Claim_Handler"] where ["Claim_Handler"] is the column name in my dataframe. However the button does not perform any action when I click on it.
Where did I do wrong?
Here is the code for the graph:
fig2 = px.box(DF2, x='Claim_Handler', y='Days_to_close',hover_data=["Claim#"])
fig2.update_layout(
title='Average days to close for Claims Closed in last 5 years',
xaxis = dict(
rangeslider = dict(
visible=True,
thickness=0.05
)
),
yaxis = dict(
),
barmode='stack',
paper_bgcolor='#FFFFFF',
showlegend=True
)
fig2.update_layout(
updatemenus=[
dict(
type = "buttons",
direction = "left",
buttons=list([
dict(
args=["Claim_Handler"],
label="DH",
method="update"
),
dict(
args=["Claim_Handler"],
label="DT",
method="update"
)
])
),]
)
fig2.show(renderer="iframe")
This question already has answers here:
Sort a pandas dataframe series by month name
(6 answers)
Closed 8 months ago.
I write a function to create barplot based on the column provide:
def bar_plot(dataset, col, figsize=(16,8)):
fig, ax = plt.subplots(figsize=figsize)
for loc in ['bottom', 'left']:
ax.spines[loc].set_visible(True)
ax.spines[loc].set_linewidth(2)
ax.spines[loc].set_color('black')
data = dataset[col].value_counts().reset_index()
ax = sns.barplot(data=data,x=col,y='index',orient='h', linewidth=1, edgecolor='k',color='#005EB8')
plt.title(f'Change counts by: {col.capitalize()}', size=16, fontweight='bold', color='#425563')
ax.set_ylabel('')
for p in ax.patches:
width = p.get_width()
plt.text(p.get_width(),
p.get_y()+.55*p.get_height(),
round(width),
va='center',
color='#425563')
When I provide the month in number, the plot is showing OK like below:
However, if I provide the full month name the last two values (Nov and Dec) are mingled in the plot:
I have been researching on it for some time now (I adjusted the yticks, ylim, etc.), but it seems without any luck so far. I can do with the month in number, but how can I fix this?
The issue was when I assigned month name in categorical order. I missed a "," between November and December. The issue is clear now after I insert the "," in that line of code.
month_order = ['January', 'February', 'March', 'April', 'May','June','July','August','September', 'October','November''December']
raw_df['month_name'] = pd.Categorical(raw_df.month_name,categories=month_order,ordered=True)
This question already has answers here:
Matplotlib pie chart: Show both value and percentage
(2 answers)
Closed 12 months ago.
we are trying with the below code to get the pie charts but we can only see the percentage in pie chart for each category and unable to print its exact values along with percentage.
dfinfoofbuss = pd.read_csv("file.csv", header=None)
dfinfoofbuss.columns = ['ID', 'INFO']
dfinfoofbuss['VALUE_INFO'] = dfinfoofbuss['ID'].str.split('_').str[1]
dfinfoofbusscnt = dfinfoofbuss.groupby(['VALUE_INFO']).size().reset_index(name='COUNT_INFO')
print("dfinfoofbusscnt:",dfinfoofbusscnt)
plotvar3 = dfinfoofbusscnt.groupby(['VALUE_INFO']).sum().plot(kind='pie' ,title='pie chart', figsize=(6,6), autopct='%.2f', legend = False, use_index=False, subplots=True, colormap="Pastel1")
fig3 = plotvar3[0].get_figure()
fig3.savefig("Info.jpg")
Sample Data
VALUE_INFO CountInfo
abc 1
defair 2
cdf 109
aggr 1
sum 1
normal 2
dev 1
Is there a way to print its original values along with percentage in pie chart.. Pls suggest
You will likely need to write your own custom function to get both value and percentage as labels.
Try:
def formatter(x):
return f"{total*x/100:.0f} ({x:.2f})%"
total = sum(dfinfoofbusscnt["CountInfo"])
plotdata = dfinfoofbusscnt.groupby("VALUE_INFO").sum()
>>> plotdata.plot(kind='pie',
title='pie chart',
figsize=(6,6),
autopct=formatter,
colormap="Pastel1",
legend=False,
subplots=True
)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am new to plotly. I am trying to create a countplot in plotly. I am reading a dataframe and here are my columns and values in the dataframe.
Name Defect severity
User1 Medium
User1 Medium
User1 High
User2 High
Here's how I would like the final graph to be shown
Can anyone suggest me how to code in Plotly?
You can do it with two lines of code, with the help of pandas groupby and plotly's barmode attribute.
Plotly's bar chart has a specific attribute to control how to show the bars, it's called barmode, quoting the API documentation:
barmode: str (default 'relative')
One of 'group', 'overlay' or 'relative' In 'relative' mode,
bars are stacked above zero for positive values and below zero for
negative values. In 'overlay' mode, bars are drawn on top of one
another. In 'group' mode, bars are placed beside each other.
See the bar chart documentation for examples.
Now, for your example:
# import needed libraries
import pandas as pd
import plotly.express as px
# some dummy dataset
df = pd.DataFrame(
{
"Name": ["User1", "User1", "User1", "User2"],
"Defect severity": ["Medium", "Medium", "High", "High"],
}
)
You need to group by both Name and Defect severity columns, and then use the count aggregating function (I recommend you take a look at this question)
df = df.groupby(by=["Name", "Defect severity"]).size().reset_index(name="counts")
The data now will look like the following:
Name
Defect severity
counts
0
User1
High
1
1
User1
Medium
2
2
User2
High
1
Finally, you can use plotly bar chart:
px.bar(data_frame=df, x="Name", y="counts", color="Defect severity", barmode="group")
The chart would be:
There you go! with only two lines of code, you got a nice grouped bar chart.
I created almost all what you want. Unfortunately, I did not find a way to set the title in the legend correctly(annotations is not good parameter to set a legend title). And to display numbers (1.0,2.0) it is necessary to create an additional column with values (column - df["Severity numbers"]).
Code:
# import all the necessaries libraries
import pandas as pd
import plotly
import plotly.graph_objs as go
# Create DataFrame
df = pd.DataFrame({"Name":["User1","User1", "User1","User2"],
"Defect severity":["Medium","Medium","High","High"],
"Severity numbers":[1,1,2,2]})
# Create two additional DataFrames to traces
df1 = df[df["Defect severity"] == "Medium"]
df2 = df[df["Defect severity"] == "High"]
# Create two traces, first "Medium" and second "High"
trace1 = go.Bar(x=df1["Name"], y=df1["Severity numbers"], name="Medium")
trace2 = go.Bar(x=df2["Name"], y=df2["Severity numbers"], name="High")
# Fill out data with our traces
data = [trace1, trace2]
# Create layout and specify title, legend and so on
layout = go.Layout(title="Severity",
xaxis=dict(title="Name"),
yaxis=dict(title="Count of defect severity"),
legend=dict(x=1.0, y=0.5),
# Here annotations need to create legend title
annotations=[
dict(
x=1.05,
y=0.55,
xref="paper",
yref="paper",
text=" Defect severity",
showarrow=False
)],
barmode="group")
# Create figure with all prepared data for plot
fig = go.Figure(data=data, layout=layout)
# Create a plot in your Python script directory with name "bar-chart.html"
plotly.offline.plot(fig, filename="bar-chart.html")
Output:
data = [
go.Bar(
y=coach_sectors['Sectors'].value_counts().to_dense().keys(),
x=coach_sectors['Sectors'].value_counts(),
orientation='h',
text="d",
)]
layout = go.Layout(
height=500,
title='Sector/ Area of Coaches - Combined',
hovermode='closest',
xaxis=dict(title='Votes', ticklen=5, zeroline=False, gridwidth=2, domain=[0.1, 1]),
yaxis=dict(title='', ticklen=5, gridwidth=2),
showlegend=False
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='Sector/ Area of Coaches - Combined')