Plotting Points in Basemap python - python-3.x

I want to plot the map of a ship data. I am using the following code:
with open ('Data.txt', 'r',encoding = 'utf-8') as f:
d = json.load(f)
# create a dataFrame
df = pd.DataFrame(([dict(id=data['id'],
X = data['x'],
Y = data['y'],
)
for data in d['features']]))
lat = df['X'].values
lon = df['Y'].values
margin = 1 # create a margin for the maps
lat_min = min(lat) - margin
lat_max = max(lat) + margin
lon_min = min(lon) - margin
lon_max = max(lon) + margin
# create a map
m = Basemap(llcrnrlon= lon_min,
llcrnrlat= lat_min,
urcrnrlon = lon_max,
urcrnrlat= lat_max,
lat_0= (lat_max - lat_min) / 2,
lon_0= (lon_max - lon_min) / 2,
projection= 'merc',
resolution= 'h',
area_thresh= 10,
)
m.drawcoastlines() # draw a coastlines
m.drawcounties(zorder=20) # draw a countries map in graph
m.drawstates()
m.drawmapboundary(fill_color= '#46bcec')
m.fillcontinents(color= 'white', lake_color= '#85A6D9')
lons, lats = m(lon, lat)
m.scatter(lons, lats, marker = 'o', zorder= 5, s= 5, c= 'g', )
plt.title('Give a proper title')
plt.show()
But while I run the code, it gives me following error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 2: invalid continuation byte in the following line:
m.drawcounties(zorder=20)
I dont know how to fix it.

Related

Multiple Lables on X-Axis in Plotly Python

I need to create a bar chart with time series values on the x-axis but they should be in layers, the example of the graph below.[![desired version][1]][1]
Right now I managed to get this for now: [![my version][2]][2]
[1]: https://i.stack.imgur.com/PQnc5.png
[2]: https://i.stack.imgur.com/1Z1aC.png
The code for the graph is here:
#creating traces for the bar chart trace_desks_popl = go.Bar(
x=df_estate_desks['Time Slot'],
y=df_estate_desks['Occupancy x Hour'],
name='Desks',
marker_color = '#26A2ED'
)
trace_meeting_popl = go.Bar(
x=df_estate_meet['Time Slot'],
y=df_estate_meet['Population x Hour'],
name='Meeting Rooms, Offices & Breakout Spaces',
marker_color = '#41C572'
)
#creating the stack bar chart data_estate_popl=[trace_desks_popl, trace_meeting_popl] layout_estate_popl= go.Layout(
barmode= 'stack',
title='Total Estate Population',
xaxis=dict(title='Time'),
yaxis=dict(title='Number of People'),
template="simple_white",
height = 700,
width=1000,
bargap=0.03
) fig_estate_popl= go.Figure(data=data_estate_popl, layout=layout_estate_popl)
#adding the line for average population avg_estate_popl = round((df_estate_meet['Population x Hour'] + df_estate_desks['Occupancy x Hour']).mean()) fig_estate_popl.layout.xaxis2 = go.layout.XAxis(overlaying='x', range=[0, 2], showticklabels=False) fig_estate_popl.add_scatter(x = [0, 2], y = [avg_estate_popl, avg_estate_popl], mode= 'lines+text', xaxis='x2', line_dash ='dot', marker_color = 'Grey',
text='Avg: ' + str(avg_estate_popl),
textposition='top left',
textfont=dict(color='Black'),
name='citations',
showlegend=False)
#adding the line for minimum population min_estate_popl = round((df_estate_meet['Population x Hour'] + df_estate_desks['Occupancy x Hour']).min()) fig_estate_popl.add_scatter(x = [0, 2], y = [min_estate_popl, min_estate_popl], mode= 'lines+text', xaxis='x2', line_dash ='dot', marker_color = 'Grey',
text='Min: ' + str(min_estate_popl),
textposition='top left',
textfont=dict(color='Black'),
name='citations',
showlegend=False)
#adding the line for maximum population max_estate_popl = round((df_estate_meet['Population x Hour'] + df_estate_desks['Occupancy x Hour']).max()) fig_estate_popl.add_scatter(x = [0, 2], y = [max_estate_popl, max_estate_popl], mode= 'lines+text', xaxis='x2', line_dash ='dot', marker_color = 'Grey',
text='Max: ' + str(max_estate_popl),
textposition='top left',
textfont=dict(color='Black'),
name='citations',
showlegend=False)
fig_estate_popl.show()
I can add the dictionary of the dataframes I used if needed. Thank you!

I am trying to create a population pyramid graph using Dash with Plotly

i have a directory containing three files, years.csv, 2014.csv and 2015.csv. i want to plot a population pyramid graph for the two files but i want pandas to pick the dataframe from the years.csv with respect to the slider value.
my years.csv looks like, on the slider when i select 2014, from the code you can see, its an int that i convert into a string and append .csv to it. but all i want is that final string interpreted as df = pd.read_csv('2014.csv') so that i can be able to generate graphs of all the years as long as that file is in the directoy.
years
0
2014(2014.csv)
1
2015(2015.csv)
from dash import Dash, dcc, html, Input, Output
# import plotly.express as px
import plotly.graph_objects as gp
import pandas as pd
# df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
df = pd.read_csv('years.csv')
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(id='graph-with-slider'),
dcc.Slider(
df['year'].min(),
df['year'].max(),
step=None,
value=df['year'].min(),
marks={str(year): str(year) for year in df['year'].unique()},
id='year-slider'
)
])
#app.callback(
Output('graph-with-slider', 'figure'),
Input('year-slider', 'value'))
def update_figure(selected_year):
new_df = str(df[df.year == selected_year]) + ".csv"
print(new_df)
# fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",
# size="pop", color="continent", hover_name="country",
# log_x=True, size_max=55)
y_age = new_df['Age']
x_M = new_df['Male']
x_F = new_df['Female'] * -1
# fig.update_layout(transition_duration=500)
# Creating instance of the figure
fig = gp.Figure()
# Adding Male data to the figure
fig.add_trace(gp.Bar(y= y_age, x = x_M,
name = 'Male',
orientation = 'h'))
# Adding Female data to the figure
fig.add_trace(gp.Bar(y = y_age, x = x_F,
name = 'Female', orientation = 'h'))
# Updating the layoutout for our graph
fig.update_layout(title = 'Population Pyramid of Uganda-2015',
title_font_size = 22, barmode = 'relative',
bargap = 0.0, bargroupgap = 0,
xaxis = dict(tickvals = [-600000, -400000, -200000,
0, 200000, 400000, 600000],
ticktext = ['6k', '4k', '2k', '0',
'2k', '4k', '6k'],
title = 'Population in Thousands',
title_font_size = 14)
)
# fig.show()
return fig
if __name__ == '__main__':
app.run_server(debug=True)

Matplotlib fuzzy near 0

Hi all, two questions:
First: Can anyone tell me what that fuzzy scrible near the 0 on the x and y axis is and how to remove it?
Second: I know that rects1 output ['42', '12', '167', '80', '197', '210', '41'] why is it showing 0,1,2,3,4,5,6? what am i missing?
ylst = []
xlst = []
xlst1 = []
figure = Figure(figsize=(9, 6), dpi=180)
for xgrp in get_days_week(3):
xlst.append(media_dia(xgrp).get("totmedia<1h", "ERRO"))
xlst1.append(tempo_dia(xgrp).get("tot_viag", "ERRO"))
ylst.append(str(xgrp))
x = np.arange(len(ylst)) # the label locations
y = np.arange(len(xlst1))
width = 0.25 # the width of the bars
figure, ax = plt.subplots()
rects1 = ax.bar(x - width / 2, xlst, width, label="N veiculos com media viagem < 1h")
rects2 = ax.bar(x + width / 2, xlst1, width, label="Total Viagens")
figure.set_figheight(6)
figure.set_figwidth(8)
ax.set_title(titulo)
ax.legend()
ax.set_xlabel(xname)
#ax.set_ylabel(yname)
ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)
ax.set_xticks(x)
ax.set_xticklabels(ylst)
# ax.set_yticks(y)
# ax.set_yticklabels(xlst1)
print("::: ",y)
print("-> ",xlst1)
# ax.set_yticklabels(np.arange(200))
figure.tight_layout()
canvas = FigureCanvasTkAgg(figure, graphframe)
canvas.get_tk_widget().grid(row=1, column=col)
Im sorry for the two questions but since its the same code and are problably connected i hope its alright.

Unable to plot the data point using Bokeh and Python- shows empty layout

I have a dataframe that has the following values. I am looking to plot them on an interactive graph using Bokeh.
locs = ['a', 'b', 'c']
prime_vals = [1000, 54, 457]
sub_vals = [0, 112, 34]
my_dict = {'loc' : locs, 'prime' : prime_vals, 'sub' : sub_vals}
df = pd.DataFrame(my_dict)
df
*I want the 'prime' and 'sub' to be two different checkboxes in the visualization. One could select both of them (prime and sub) and see the values with respect to 'loc' or see their values individually.
Below is the code I have, but it gives me the below image only- without any values.
p = figure(plot_width=1200, plot_height = 800)
aline = p.line(df["locs"], df['prime_vals'], line_width=2,
color=Viridis4[0])
bline = p.line(df["locs"], df['sub_vals'], line_width=2,
color=Viridis4[3])
p.yaxis.axis_label = 'x - axis label '
p.xaxis.axis_label = 'y - axis label'
legend = Legend(items=[("Prime", [aline]),("Sub", [bline])], location=(0, 450))
t = Title()
t.text = 'Prime and sub roles over various offices'
p.title = t
p.add_layout(legend, 'left')
checkboxes = CheckboxGroup(labels=list(['Prime', 'Sub']), active=[0, 1])
callback = CustomJS(code="""aline.visible = false; // aline and etc.. are
bline.visible = false; // passed in from args
// cb_obj is injected in thanks to the callback
if (cb_obj.active.includes(0)){aline.visible = true;}
// 0 index box is aline
if (cb_obj.active.includes(1)){bline.visible = true;} """,
args={'aline': aline, 'bline': bline})
checkboxes.js_on_click(callback)
output_file('some_name.html')
show(row(p, checkboxes))
I am unable to understand why the data points are not being plotted.

How can I use the plotly dropdown menu feature to update the z value in my choropleth map?

I just want to create a menu on the plot where I'm able to change the z-value in data only. I tried looking at other examples on here: https://plot.ly/python/dropdowns/#restyle-dropdown but it was hard since the examples were not exactly similar to my plot.
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
data = [go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = [
[0, "rgb(5, 10, 172)"],
[0.35, "rgb(40, 60, 190)"],
[0.5, "rgb(70, 100, 245)"],
[0.6, "rgb(90, 120, 245)"],
[0.7, "rgb(106, 137, 247)"],
[1, "rgb(220, 220, 220)"]
],
autocolorscale = False,
reversescale = True,
marker = go.choropleth.Marker(
line = go.choropleth.marker.Line(
color = 'rgb(180,180,180)',
width = 0.5
)),
colorbar = go.choropleth.ColorBar(
tickprefix = '$',
title = 'GDP<br>Billions US$'),
)]
layout = go.Layout(
title = go.layout.Title(
text = '2014 Global GDP'
),
geo = go.layout.Geo(
showframe = False,
showcoastlines = False,
projection = go.layout.geo.Projection(
type = 'equirectangular'
)
),
annotations = [go.layout.Annotation(
x = 0.55,
y = 0.1,
xref = 'paper',
yref = 'paper',
text = 'Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
showarrow = False
)]
)
fig = go.Figure(data = data, layout = layout)
py.iplot(fig, filename = 'd3-world-map')
It's been a while since this was asked, but I figured it was still worth answering. I can't speak to how this might have changed since it was asked in 2019, but this works today.
First, I'll provide the code I used to create the new z values and the dropdown menu, then I'll provide all of the code I used to create these graphs in one chunk (easier to cut and paste...and all that).
This is the data I used for the alternate data in the z field.
import plotly.graph_objects as go
import pandas as pd
import random
z2 = df['GDP (BILLIONS)'] * .667 + 12
random.seed(21)
random.shuffle(z2)
df['z2'] = z2 # example as another column in df
print(df.head()) # validate as expected
z3 = df['GDP (BILLIONS)'] * .2 + 1000
random.seed(231)
random.shuffle(z3) # example as a series outside of df
z4 = df['GDP (BILLIONS)']**(1/3) * df['GDP (BILLIONS)']**(1/2)
random.seed(23)
random.shuffle(z4)
z4 = z4.tolist() # example as a basic Python list
To add buttons to change z, you'll add updatemenus to your layout. Each dict() is a separate dropdown option. At a minimum, each button requires a method, a label, and args. These represent what is changing (method for data, layout, or both), what it's called in the dropdown (label), and the new information (the new z in this example).
args for changes to data (where the method is either restyle or update) can also include the trace the change applies to. So if you had a bar chart and a line graph together, you may have a button that only changes the bar graph.
Using the same structure you have:
updatemenus = [go.layout.Updatemenu(
x = 1, xanchor = 'right', y = 1.15, type = "dropdown",
pad = {'t': 5, 'r': 20, 'b': 5, 'l': 30}, # around all buttons (not indiv buttons)
buttons = list([
dict(
args = [{'z': [df['GDP (BILLIONS)']]}], # original data; nest data in []
label = 'Return to the Original z',
method = 'restyle' # restyle is for trace updates
),
dict(
args = [{'z': [df['z2']]}], # nest data in []
label = 'A different z',
method = 'restyle'
),
dict(
args = [{'z': [z3]}], # nest data in []
label = 'How about this z?',
method = 'restyle'
),
dict(
args = [{'z': [z4]}], # nest data in []
label = 'Last option for z',
method = 'restyle'
)])
)]
All code used to create this graph in one chunk (includes code shown above).
import plotly.graph_objs as go
import pandas as pd
import ssl
import random
# to collect data without an error
ssl._create_default_https_context = ssl._create_unverified_context
# data used in plot
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
# z values used in buttons
z2 = df['GDP (BILLIONS)'] * .667 + 12
random.seed(21)
random.shuffle(z2)
df['z2'] = z2 # example as another column in the data frame
print(df.head()) # validate as expected
z3 = df['GDP (BILLIONS)'] * .2 + 1000
random.seed(231)
random.shuffle(z3) # example as a series outside of the data frame
z4 = df['GDP (BILLIONS)']**(1/3) * df['GDP (BILLIONS)']**(1/2)
random.seed(23)
random.shuffle(z4)
z4 = z4.tolist() # example as a basic Python list
data = [go.Choropleth(
locations = df['CODE'], z = df['GDP (BILLIONS)'], text = df['COUNTRY'],
colorscale = [
[0, "rgb(5, 10, 172)"],
[0.35, "rgb(40, 60, 190)"],
[0.5, "rgb(70, 100, 245)"],
[0.6, "rgb(90, 120, 245)"],
[0.7, "rgb(106, 137, 247)"],
[1, "rgb(220, 220, 220)"]],
reversescale = True,
marker = go.choropleth.Marker(
line = go.choropleth.marker.Line(
color = 'rgb(180,180,180)', width = 0.5)),
colorbar = go.choropleth.ColorBar(
tickprefix = '$',
title = 'GDP<br>Billions US$',
len = .6) # I added this for aesthetics
)]
layout = go.Layout(
title = go.layout.Title(text = '2014 Global GDP'),
geo = go.layout.Geo(
showframe = False, showcoastlines = False,
projection = go.layout.geo.Projection(
type = 'equirectangular')
),
annotations = [go.layout.Annotation(
x = 0.55, y = 0.1, xref = 'paper', yref = 'paper',
text = 'Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
showarrow = False
)],
updatemenus = [go.layout.Updatemenu(
x = 1, xanchor = 'right', y = 1.15, type = "dropdown",
pad = {'t': 5, 'r': 20, 'b': 5, 'l': 30},
buttons = list([
dict(
args = [{'z': [df['GDP (BILLIONS)']]}], # original data; nest data in []
label = 'Return to the Original z',
method = 'restyle' # restyle is for trace updates only
),
dict(
args = [{'z': [df['z2']]}], # nest data in []
label = 'A different z',
method = 'restyle'
),
dict(
args = [{'z': [z3]}], # nest data in []
label = 'How about this z?',
method = 'restyle'
),
dict(
args = [{'z': [z4]}], # nest data in []
label = 'Last option for z',
method = 'restyle'
)])
)]
)
fig = go.Figure(data = data, layout = layout)
fig.show()

Resources