Python 3 does not show the barchart - python

I am trying to make this bargraph appear in the python run screen. But for some reason, it does not show the graph on the screen. However, if I put this code on the google online coding website, it shows the bar graph fine. Can anyone let me know what the problem is?
import pandas as pd
import plotly.express as px
df = pd.read_csv("Diversity2.csv")
df = df.groupby(['School','White'], as_index=False)[['School']].sum()
# df = df.groupby(['School','White']).sum().plot(kind='bar')
df['White']=df['White'].astype(float)
# df.plot(kind='bar', x='School', y='White', figsize=(20,10))
barchart = px.bar(
data_frame=df,
x="School",
y="White",
color="School",
opacity=0.9,
orientation="v",
barmode='overlay')
barchart.show()

Related

Histogram "CSV Printing" Error in plotly.express python

So I'm trying to create a histogram using Python, and was wondering why my code wasn't working.
import plotly.express as px
data = pd.read_csv("/kaggle/input/dataset1csv/test.csv")
print(data.head())
data = data
figure = px.histogram(data, x = "sex",
color = "age_approx",
title= "Datadistribution")
figure.show()
After running this, I just get some data printed out to me.
What am I doing wrong?

How can i make this time series graph interactive?

I am new to Python and Pandas so any help is much appreciated.
I am trying to make the graph below interactive, it would also be good to be able to choose which attributes show rather than them all.
Here is what I have so far
df.set_index('Current Year').plot(rot=45)
plt.xlabel("Year",size=16)
plt.ylabel("",size=16)
plt.title("Current year time series plot", size=18)
I know that i need to import the following import plotly.graph_objects as go but no idea how to implement this with the above time series graph. Thanks
EDIT
I am getting this error when trying to enter my plotted data.
All you need is:
df.plot()
As long as you import the correct libraries and set plotly as the plotting backend for pandas like this:
import pandas as pd
pd.options.plotting.backend = "plotly"
df = pd.DataFrame({'year':['2020','2021','2022'], 'value':[1,3,2]}).set_index('year')
fig = df.plot(title = "Current year time series plot")
fig.show()
Plot:
Complete code:
import pandas as pd
pd.options.plotting.backend = "plotly"
df = pd.DataFrame({'year':['2020','2021','2022'], 'value':[1,3,2]}).set_index('year')
fig = df.plot(title = "Current year time series plot")
fig.show()

Plotly bar chart not ascending/descending

I have a bar chart in plotly that I have produced, however, it is not in any type of order. How would I sort to ascending or descending?
What I am doing:
fig = px.bar(data, x='Old_SKU', y='u_power')
fig = data.sort_values('u_power', ascending=True)
fig.show()
I'm not sure what your desired output is, or what your data looks like. In any case fig in plotly terms is normaly a plotly figure object. When you're running fig = data.sort_values('u_power', ascending=True) you're not building a figure, but sorting a dataframe. So far I can only imagine that you'd like to sort a dataset that looks like this:
... into this:
Or maybe you're expecting a continuous increase or decrease? In that case you will have to share a dataset. Nevertheless, with a few tweaks depending on your dataset, the following snippet should not be far from a working solution:
import plotly.express as px
import numpy as np
import pandas as pd
var = np.random.randint(low=2, high=6, size=20).tolist()
data = pd.DataFrame({'u_power':var,
'Old_SKU':np.arange(0, len(var))})
# fig = px.bar(data, x='Old_SKU', y='u_power', barmode='stack')
fig = px.bar(data.sort_values('u_power'), x='Old_SKU', y='u_power', barmode='stack')
fig.show()

Plotly: How to plot time series in Dash Plotly

I've searched for days and didn't find an answer. How can I plot a time series data in Dash Plotly as a linegraph with selectable lines?
My data (pandas dataframe) describes GDP of different countrys. Index is country, column is years.
I don't find a solution to pass the data to Dash Plotly linegraph. What are my x and y values?
fig = px.line(df, x=?, y=?)
By the looks of it, the solution in your example should be:
fig = px.line(df, x=df.index, y = df.columns)
Plot 1 - plot by columns as they appear in your dataset
From here, if you'd like to display countries in the legend and have time on the x-axis, you can just add df = df.T into the mix and get:
Plot 2 - transposed dataframe to show time on the x-axis
Details
There's a multitude of possibilites when it comes to plotting time series with plotly. Your example displays a dataset of a wide format. With the latest versions, plotly handles both datasets of long and wide format elegantly straight out of the box. If you need specifics of long and wide data in plotly you can also take a closer look here.
The code snippet below uses the approach described above, but in order for this to work for you exactly the same way, your countries will have to be set as the dataframe row index. But you've stated that they are, so give it a try and let me know how it works out for you. And one more thing: you can freely select which traces to display by clicking the years in the plot legend. The figure produced by the snippet below can also be directly implemented in Dash by following the steps under the section What About Dash? here.
Complete code:
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
import plotly.io as pio
# sample dataframe of a wide format
np.random.seed(5); cols = ['Canada', 'France', 'Germany']
X = np.random.randn(6,len(cols))
df=pd.DataFrame(X, columns=cols)
df.iloc[0]=0;df=df.cumsum()
df['Year'] = pd.date_range('2020', freq='Y', periods=len(df)).year.astype(str)
df = df.T
df.columns = df.iloc[-1]
df = df.head(-1)
df.index.name = 'Country'
# Want time on the x-axis? ###
# just include:
# df = df.T
##############################
# plotly
fig = px.line(df, x=df.index, y = df.columns)
fig.update_layout(template="plotly_dark")
fig.show()

How to plot green and red arrows over a plotly CandleStick graph?

I have tried to plot the Candle Sticks for my data using the plotly library with Python. Using the typical plotting way, I got the following graph:
Candle = go.Candlestick(x=stock.index,
open=stock.open,
high=stock.high,
low=stock.low,
close=stock.close
)
Output:
I was expecting to draw the image is something like the following:
See the up green arrow and the down red arrow. I want to know how to plot that.
I don't know which one is the logic for selecting arrows but you can play from here. First download data from Yahoo-finance TESLA and then
import plotly.offline as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
stock = pd.read_csv("~/Downloads/TSLA.csv")
d=3
stock["Marker"] = np.where(stock["Open"]<stock["Close"], stock["High"]+d, stock["Low"]-d)
stock["Symbol"] = np.where(stock["Open"]<stock["Close"], "triangle-up", "triangle-down")
stock["Color"] = np.where(stock["Open"]<stock["Close"], "green", "red")
Candle = go.Candlestick(x=stock.Date,
open=stock.Open,
high=stock.High,
low=stock.Low,
close=stock.Close
)
Trace = go.Scatter(x=stock.Date,
y=stock.Marker,
mode='markers',
name ='markers',
marker=go.Marker(size=20,
symbol=stock["Symbol"],
color=stock["Color"])
)
py.plot([Candle, Trace])

Categories