Exemplo n.º 1
0
        date_options[weeks] = date_item.strftime("%b %d")
    else:
        date_options[weeks] = date_item.strftime("%b %d")
    weeks = weeks + 1

#Pick a default date
inprogress = data_US['date'][data_US.index[-3]]
first_date = data_US['date'][data_US.index[0]]
last_date = data_US['date'][data_US.index[-1]]

#Set up the charts
import plotly.express as px
import plotly.graph_objects as go

#fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)
fig = px.choropleth()
bar1 = px.bar()
bar2 = px.bar()

colorscale = [
    "#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef", "#b3d2e9",
    "#9ecae1", "#85bcdb", "#6baed6", "#57a0ce", "#4292c6", "#3082be",
    "#2171b5", "#1361a9", "#08519c", "#0b4083", "#08306b"
]  # or px.colors.sequential.Plasma

#Style the charts
plotcfg = {'displayModeBar': False}
#fig1.update_xaxes(rangeslider_visible=True)
fig.update_layout(height=500,
                  margin=dict(l=0, r=0, b=0, t=0, pad=0),
                  coloraxis_colorbar=dict(title="Z-score"),
Exemplo n.º 2
0
    fig = px.line(y=data,
                  x=year,
                  template='plotly_dark',
                  title=country_name + ' Population in largest city',
                  labels=dict(x="Years", y="Population in largest city"))
    fig.show()


a = input('Your Country Name: __ ')

try:
    specific_country(a)
except:
    print('Invalid Country Name')

df = df.sort_values(by='2019', ascending=False)

df = pd.melt(df, id_vars=['Country Name', 'Country Code'], value_vars=lista)
print(df)
fig = px.choropleth(
    df,  # Input Dataframe
    locations="Country Code",  # identify country code column
    color="value",  # identify representing column
    hover_name="Country Name",  # identify hover name
    animation_frame="variable",  # identify date column
    projection="natural earth",  # select projection
    color_continuous_scale='Peach',  # select prefer color scale
    range_color=[-6, 6]  # select range of dataset
)
fig.show()
Exemplo n.º 3
0

# In[ ]:


dates = date_cols*len(covid_conf['Country/Region'])

values = np.array([list(i) for i in covid_conf[date_cols].iloc]).flatten()
data = pd.DataFrame({'country':countries, 'date':dates, 'confirmed':values})
data


# In[ ]:


fig = px.choropleth(data, locations='country', color='confirmed', animation_frame='date')
fig.show()


# In[ ]:





# In[ ]:




Exemplo n.º 4
0
#aggregate based on states
agg_state = (extra_data.drop(['Metro_meta','Year','Month','Labor_Force',
                              'Employment',
                              'Unemployment','date',	'Metro'], axis=1))
agg_state=agg_state.groupby('States').mean()

# In[ ]:

type(list(agg_state.index))

import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt

fig = go.Figure(px.choropleth(locations=agg_state.index, locationmode="USA-states", color= agg_state.values, scope="usa"))

fig.update_layout(title="Average Unemployment Rate by State")

fig.data[-1].showlegend = True
fig.update_layout(legend_title='<b> Unemployment Rate </b>')
fig.show()
# In[ ]:
#plot avg unemployment by county
#first figure out how to ID county -- use FIPS code -- this is in the metro metadata
#isolate the fips codes
#get state level information
fips = []
#from the metro meta data, isolate just the fips 
for i in range(4,142564):
  fips.append(str((extra_data['Metro_meta'][i][2:7]).strip()))
Exemplo n.º 5
0
data.info()


# In[7]:


data.describe()


# ## Visualiize the data with plotly

# In[8]:


fig = px.choropleth(data,locations='Country',locationmode='country names',color='Confirmed',animation_frame='Date')
fig.update_layout(title='Choropleth Map of Confirmed Cases -till today',template="plotly_dark")
fig.show()


# In[9]:


fig = px.choropleth(data,locations='Country',locationmode='country names',color='Confirmed',animation_frame='Date',scope='africa')
fig.update_layout(title='Choropleth Map of Confirmed Cases - Africa till today',template="plotly_dark")
fig.show()


# ## Spread over Time

# In[10]:
Exemplo n.º 6
0
- Statistics for Data Scientists: Sat, 10:30-12:00
- How to Win TAMU Datathon: Sat, 13:00-14:00
- Data Wrangling: Sat, 17:00-18:15
- Data Visualization: Sat, 18:30-19:45
- Machine Learning Part 1 - Theory: Sat, 20:00-21:15
- Machine Learning Part 2 - Applied: Sat, 21:30-22:45
""")

df = pd.read_csv(
    'https://drive.google.com/uc?id=1hSMhl-JeTCX-t72KjhasTQoL1LdWSRhw')
st.write(df.head())

df_1 = px.data.gapminder()
fig = px.choropleth(df_1,
                    locations="iso_alpha",
                    color="lifeExp",
                    hover_name="country",
                    animation_frame="year",
                    range_color=[20, 80])
st.write(fig)

movehub_rating = "None"  #@param ["None", "Low", "Med", "High"]
purchase_power = "High"  #@param ["None", "Low", "Med", "High"]
health_care = "Low"  #@param ["None", "Low", "Med", "High"]
quality_of_life = "None"  #@param ["None", "Low", "Med", "High"]
pollution = "None"  #@param ["None", "Low", "Med", "High"]
crime_rating = "None"  #@param ["None", "Low", "Med", "High"]

weights = [
    movehub_rating,
    purchase_power,
    health_care,
Exemplo n.º 7
0
plot_values = {"Positive tests":"positive",
               "Total tests":"totalTestResults",
               "Percent increase (rolling day-to-day)":"perc_increase",
               "Percent increase (five-day rolling average)":"perc_five_increase",
               "Percent deaths":"perc_death",
               "Percent hospitalized":"perc_hosp"}



mostrecent = sorted(data["date"],reverse=True)[0]

tmp = data.loc[data["date"] == mostrecent][["state","positive"]].dropna()
tmp["state"].values

state_map_fig = px.choropleth(locations=tmp["state"].values,
                                locationmode="USA-states",
                                color=np.log10(tmp["positive"].replace(0,1)).values,
                                scope="usa")

app.layout = html.Div([
    html.H1('COVID-19 statistics from covidtracking.com'),
    dcc.Tabs(id="plot-tabs", 
    value='state-positive', 
    children = [
        dcc.Tab(label='State Stats over Time', value='state-positive'),
        dcc.Tab(label='US State Heatmap', value='us-state-map'),
        
            ]),
    html.Div(id='plot-tabs-contents') # generate from render content function below, as callback.
])

@app.callback(Output('plot-tabs-contents', 'children'),
Exemplo n.º 8
0
def update_graph(cat_selected, date_selected):
    print(cat_selected)
    print(date_selected)
    date = YEARS.get(date_selected)
    only_one_day = our_df[our_df['date'] == date]
    if cat_selected == 'ActPerPop':
        fig = px.choropleth(
            only_one_day,
            locations="isocode",
            color="ActPerPop",  # This will determine the color
            hover_name="country",  # column to add to hover information
            # template = 'plotly_dark' ,
            width=1300,
            height=500,
            color_continuous_scale=px.colors.sequential.YlOrRd)
    if cat_selected == 'CnfPerPop':
        fig = px.choropleth(
            only_one_day,
            locations="isocode",
            color="CnfPerPop",  # This will determine the color
            hover_name="country",  # column to add to hover information
            # template = 'plotly_dark' ,
            width=1300,
            height=500,
            color_continuous_scale=px.colors.sequential.YlOrRd)

    if cat_selected == 'RecPerCnf':
        fig = px.choropleth(
            only_one_day,
            locations="isocode",
            color="RecPerCnf",  # This will determine the color
            hover_name="country",  # column to add to hover information
            # template = 'plotly_dark'
            width=1300,
            height=500,
            color_continuous_scale=px.colors.sequential.YlOrRd)

    if cat_selected == 'DecPerCnf':
        fig = px.choropleth(
            only_one_day,
            locations="isocode",
            color="DecPerCnf",  # This will determine the color
            hover_name="country",  # column to add to hover information
            # template = 'plotly_dark' ,
            width=1300,
            height=500,
            color_continuous_scale=px.colors.sequential.YlOrRd)

    fig.update_layout(
        # title = str(date_selected) + " Worst hit countries" ,
        title="Date Selected is : " + date,
        # width = 1200,
        autosize=True,
        # margin = dict(l = 40 , r = 40 , t = 40 , b = 40) ,
        paper_bgcolor="LightSteelBlue",
    )
    #
    # if "layout" in figure :
    # 	lat = figure["layout"]["mapbox"]["center"]["lat"]
    # 	lon = figure["layout"]["mapbox"]["center"]["lon"]
    # 	zoom = figure["layout"]["mapbox"]["zoom"]
    # else :
    lat = 38.72490
    lon = -95.61446
    zoom = 3.5

    layout = dict(
        mapbox=dict(
            layers=[],
            accesstoken=mapbox_access_token,
            style=mapbox_style,
            center=dict(lat=lat, lon=lon),
            zoom=zoom,
        ),
        hovermode="closest",
        margin=dict(r=0, l=0, t=0, b=0),
        # annotations = annotations ,
        dragmode="lasso",
    )

    # fig = dict( layout = layout)

    return fig
Exemplo n.º 9
0
import pandas as pd
import plotly.express as px

# Source for basis of mapping Script: https://gist.github.com/jbrobst
df = pd.read_csv(r"C:\Users\Arnav Joshi\OxygenNeed.csv")

fig = px.choropleth(
    df,
    geojson=
    "https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
    featureidkey='properties.ST_NM',
    locations='State',
    color='Oxygen Needed Daily(tonnes)',
    color_continuous_scale='Blues')

fig.update_geos(fitbounds="locations", visible=False)

fig.show()
Exemplo n.º 10
0
import pandas as pd
import plotly.express as px

# load in the dataset
df = pd.read_csv("../data/share-of-individuals-using-the-internet.csv")

# extract data for 2016
df_2016 = df[df['Year'] == 2016]

print(df_2016.shape)
print(df.columns)

plot = px.choropleth(
    data_frame=df_2016,
    locations='Country',
    color='Individuals using the Internet (% of population)',
    locationmode='country names',
    hover_name='Country',
    title=
    "Internet usage across countries of the world as a percentage of the total population in 2016."
)

plot.show()
Exemplo n.º 11
0
import plotly.express as px

df = px.data.election()
geojson = px.data.election_geojson()

fig = px.choropleth(df,
                    geojson=geojson,
                    color="Bergeron",
                    locations="district",
                    featureidkey="properties.district",
                    projection="mercator")

fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()
    states_geojson = json.load(file)

geojson_state_code_map = {}
for feature in states_geojson["features"]:
    feature['id'] = feature['properties']['state_code']
    geojson_state_code_map[feature['properties']['st_nm'].upper(
    )] = feature['properties']['state_code']

state_id_map = {}
with open('../library/overall_state_frequency.csv', 'r', newline='') as file:
    for row in csv.DictReader(file):
        state = row["State"]
        if state == "DELHI":
            state_id_map[state] = geojson_state_code_map["NCT OF DELHI"]
        else:
            state_id_map[state] = geojson_state_code_map[
                difflib.get_close_matches(state,
                                          geojson_state_code_map.keys())[0]]

df = pd.read_csv('../library/overall_state_frequency.csv')
df['Frequency'] = df['Frequency'].apply(lambda x: int(x))
df['id'] = df['State'].apply(lambda x: state_id_map.get(x, 0))
df['Frequency_Scale'] = np.log10(df['Frequency'])

fig = px.choropleth(df,
                    locations='id',
                    geojson=states_geojson,
                    color='Frequency',
                    scope='asia')
fig.update_geos(fitbounds="locations", visible=False)
fig.write_image("../images/overall_state_frequency.png")
def update_graph(option_slctd, data_slctd, scope_slctd, cumil_slctd):
    print(option_slctd)
    print(data_slctd)
    print(scope_slctd)
    print(cumil_slctd)
    #cumil_slctd=False
    dff1 = df1.copy()
    dff1 = dff1[dff1["month_num"] == option_slctd]
    container = "The data chosen by user is {0} and the geographical scope is {1}".format(
        data_slctd, scope_slctd)

    if (cumil_slctd == 'non_cumil'):

        if data_slctd == "deaths":
            fig = px.choropleth(
                data_frame=dff1,
                locationmode='ISO-3',
                locations='iso_code',
                scope=scope_slctd,
                color="new_deaths",
                hover_data=[
                    'location', 'new_deaths', 'hospital_beds_per_thousand'
                ],
                color_continuous_scale=px.colors.diverging.Geyser)

        elif data_slctd == "affected_cases":
            fig = px.choropleth(
                data_frame=dff1,
                locationmode='ISO-3',
                locations='iso_code',
                scope=scope_slctd,
                color="new_cases",
                hover_data=[
                    'location', 'new_cases', 'hospital_beds_per_thousand'
                ],
                color_continuous_scale=px.colors.diverging.Geyser)

        else:
            fig = px.choropleth(
                data_frame=dff1,
                locationmode='ISO-3',
                locations='iso_code',
                scope=scope_slctd,
                color="new_tests",
                hover_data=[
                    'location', 'new_tests', 'hospital_beds_per_thousand'
                ],
                color_continuous_scale=px.colors.diverging.Geyser)

    else:

        if data_slctd == "deaths":
            fig = px.choropleth(
                data_frame=dff1,
                locationmode='ISO-3',
                locations='iso_code',
                scope=scope_slctd,
                color="cumil_deaths",
                hover_data=[
                    'location', 'cumil_deaths', 'hospital_beds_per_thousand'
                ],
                color_continuous_scale=px.colors.diverging.Geyser)

        elif data_slctd == "affected_cases":
            fig = px.choropleth(
                data_frame=dff1,
                locationmode='ISO-3',
                locations='iso_code',
                scope=scope_slctd,
                color="cumil_cases",
                hover_data=[
                    'location', 'cumil_cases', 'hospital_beds_per_thousand'
                ],
                color_continuous_scale=px.colors.diverging.Geyser)

        else:
            fig = px.choropleth(
                data_frame=dff1,
                locationmode='ISO-3',
                locations='iso_code',
                scope=scope_slctd,
                color="cumil_tests",
                hover_data=[
                    'location', 'cumil_tests', 'hospital_beds_per_thousand'
                ],
                color_continuous_scale=px.colors.diverging.Geyser)

    #LineGraph
    if data_slctd == "deaths":
        img = px.line(dff3,
                      x=dff3['location'],
                      y=dff3['cumil_deaths'],
                      title='Line Graph for Total Deaths')
        #img.show()
    elif data_slctd == "affected_cases":
        img = px.line(dff3,
                      x=dff3['location'],
                      y=dff3['cumil_cases'],
                      title='Line Graph for Total Affected Cases')
    else:
        img = px.line(dff3,
                      x=dff3['location'],
                      y=dff3['cumil_tests'],
                      title='Line Graph for Total Tests')

    return container, fig, img
Exemplo n.º 14
0
covid19_us_states['confirmed_cases_category'] = covid19_us_states['confirmed'].apply(lambda x: confirmed_case_category(x))

covid19_us_states.head()

covid19_us_states['confirmed_cases_category'] = pd.Categorical(covid19_us_states['confirmed_cases_category'], ordered=True,
                   categories=['< 1000', '> 1000', '> 10000','> 50000'])

covid19_us_states.dtypes

covid19_us_states.head()

covid19_us_states['confirmed_cases_category'].unique()

import plotly.express as px
import matplotlib.pyplot as plt 
fig = px.choropleth(covid19_us_states, color='confirmed', color_continuous_scale="Rainbow",
                    locations='state', locationmode="USA-states",scope="usa")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

import plotly.express as px
import matplotlib.pyplot as plt 
fig = px.choropleth(covid19_us_states, color='deaths', color_continuous_scale="reds",
                    locations='state', locationmode="USA-states",scope="usa")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

covid19_us_states = covid19_us_data.groupby(['state','province']).agg('sum')

covid19_us_states = covid19_us_states[['confirmed','deaths','recovered']]

covid19_us_states =covid19_us_states.reset_index()
Exemplo n.º 15
0
    # GroupingBy the dataset for the map
    formated_gdf = covid_cases.groupby(['Date_x', 'Country'])[
        'Confirmed', 'Deaths', 'Recovered'].max()
    formated_gdf = formated_gdf.reset_index()
    formated_gdf['Date'] = pd.to_datetime(formated_gdf['Date_x'])
    formated_gdf['Date'] = formated_gdf['Date'].dt.strftime('%m/%d/%Y')

    formated_gdf['log_ConfirmedCases'] = np.log(formated_gdf.Confirmed + 1)
    formated_gdf['log_Deaths'] = np.log(formated_gdf.Deaths + 1)

    # Plotting the figure

    fig = px.choropleth(formated_gdf, locations="Country", locationmode='country names',
                        color="log_ConfirmedCases", hover_name="Country", projection="mercator",
                        animation_frame="Date", width=1000, height=800,
                        color_continuous_scale=px.colors.sequential.Viridis,
                        title='The Spread of COVID-19 Cases Across World')

    # Showing the figure
    fig.update(layout_coloraxis_showscale=True)
    py.offline.iplot(fig)

if query == '3':
    # reference from: https://www.kaggle.com/aestheteaman01/demographics-observation-for-pandemic-escalation
    # #Which-populations-are-at-risk-of-contracting-COVID-19?
    fig = px.choropleth(formated_gdf, locations="Country", locationmode='country names',
                        color="log_Deaths", hover_name="Country", projection="mercator",
                        animation_frame="Date", width=1000, height=800,
                        color_continuous_scale=px.colors.sequential.Viridis,
                        title='The COVID-19 Deaths Cases Across World')
just_ML = c[
    (c['Q8'] ==
     'We have well established ML methods (i.e., models in production for more than 2 years)'
     )
    |
    (c['Q8'] ==
     'We recently started using ML methods (i.e., models in production for less than 2 years)'
     )
    |
    (c['Q8'] ==
     'We use ML methods for generating insights (but do not put working models into production)'
     )]
import plotly.express as px  # Be sure to import express
fig = px.choropleth(
    countries,  # Input Pandas DataFrame
    locations="country",  # DataFrame column with locations
    color="N° of answers",  # DataFrame column with color values
    locationmode='country names',  # Set to plot
    color_continuous_scale='viridis')
fig.update_layout(title_text='2019 Kaggle survey respondents per country')

fig.show()  # Output the plot to the screen
fig = plt.figure(figsize=(15, 5))
ax1 = plt.subplot2grid((1, 2), (0, 0))
sns.countplot(c.Q1, order=c['Q1'].value_counts().index, palette='viridis')
plt.title('AGE', fontsize=15, weight='bold')

ax1 = plt.subplot2grid((1, 2), (0, 1))
sns.countplot(c.Q2, palette='viridis')
plt.title('GENDER', fontsize=15, weight='bold')
plt.show()
plt.figure(figsize=(15, 5))
Exemplo n.º 17
0
            county_data['Age_0_4'].sum(), county_data['Age_5_14'].sum(),
            county_data['Age_15_24'].sum(), county_data['Age_25_34'].sum(),
            county_data['Age_35_44'].sum(), county_data['Age_45_54'].sum(),
            county_data['Age_55_64'].sum(), county_data['Age_65_74'].sum(),
            county_data['Age_85plus'].sum()
        ])
    plt.title('Covid Cases by Age')
    st.pyplot()

    fig = px.choropleth(county_data,
                        geojson=counties,
                        locations='COUNTY',
                        color='T_positive',
                        color_continuous_scale="Viridis",
                        hover_name='COUNTYNAME',
                        hover_data=[
                            'Age_0_4', 'Age_5_14', 'Age_25_34', 'Age_35_44',
                            'Age_45_54', 'Age_55_64', 'Age_65_74', 'Age_85plus'
                        ],
                        scope="usa",
                        title="Positive Test Cases",
                        range_color=(0, 10000))
    fig.update_geos(projection={'scale': 4},
                    center={
                        'lat': 27.6648,
                        'lon': -81.5158
                    },
                    visible=False)
    st.plotly_chart(fig)
    '''
    From the data we can see that the largest age range that has tested positive for COVID-19 is 25 
Exemplo n.º 18
0
    '% of guests'] = country_data['Number of Guests'] / total_guests * 100
country_data['country'] = country_data.index
country_data.drop(columns='country', inplace=True)

fig = px.pie(
    country_data,
    values='Number of Guests',
    names=country_data.index,
    title='Home Country of Guests by %',
    template='seaborn',
)
fig.update_traces(textposition="inside", textinfo="value+percent+label")

guest_map = px.choropleth(country_data,
                          locations=country_data.index,
                          color=country_data['% of guests'],
                          hover_name=country_data.index,
                          color_continuous_scale='Viridis',
                          title="Home country of guests")

# fig.show()
# guest_map.show()

# how much do guests pay per night/person --------------------------------------

df['adr_pp'] = df['adr'] / df['total_guests']
df_guests = df.loc[df['is_canceled'] == 0]
room_prices = df[['hotel', 'reserved_room_type',
                  'adr_pp']].sort_values('reserved_room_type')

plt.figure(figsize=(8, 5))
sns.set()
Exemplo n.º 19
0
def returnJsonResult():
    if request.method == 'POST':
        data = request.data
        decodeddata = data.decode('utf-8')
        jsondata = json.loads(decodeddata)
        # print(jsondata)

        # jsondata = {"query":"Lula",
        #             "country":[],
        #             "lang":[],
        #             "verified":"",
        #             "topic":[],
        #             "tweetDateFrom":"",
        #             "tweetDateTo":"",
        #             "exactMatch":"true"}
        # jsondata = {"query":"modi",
        #             "country":["india","usa"],
        #             "lang":["en","hi"],
        #             "verified":"false",
        #             "topic":[],
        #             "tweetDateTo":"2019-08-08T00:00:00Z",
        #             "tweetDateFrom":"2019-09-07T00:00:00Z",
        #             "exactMatch":"false"}
        each_query = jsondata.get('query')

        each_query = each_query.replace(" ", "%20")
        if (each_query == ""):
            each_query = '#"*:*'
        else:
            # each_query = "text_hi%3A"+each_query+"%20or%20"+"text_en%3A"+each_query+"%20or%20"+"text_pt%3A"+each_query
            pass
        # each_query = each_query.replace(":", "\:")
        # each_query = urllib.parse.quote(each_query)
        # print(each_query)

        input_query = each_query

        ip = "18.191.55.237:8984"
        # IRModel = "IRF19P1"
        IRModel = "test"

        #country = ["india","usa"]
        country = jsondata.get('country')
        lang = jsondata.get('lang')  #["en","hi"]
        topic = jsondata.get('topic')
        #verified = "true"
        verified = jsondata.get('verified')
        tweet_date_from = jsondata.get('tweetDateFrom')
        tweet_date_to = jsondata.get('tweetDateTo')

        #http://13.59.238.116:8983/solr/IRF19P1/select?q=*%3A*&rows=20

        #topic = []#["news"]
        #inputQuery ="*%3A*"
        exact_match = jsondata.get('exactMatch')
        filter_query = ""
        append = "%20OR%20"
        and_append = "&fq="
        #2019-09-07T00:00:00Z TO 2019-09-08T00:00:00Z
        #tweet_date%3A%5B2019-09-07T00%3A00%3A00Z%20TO%202019-09-08T00%3A00%3A00Z%5D%20

        if (len(country) > 0):
            filter_query = "fq="
        else:
            filter_query = ""

        if (len(country) > 0):
            filter_query = filter_query + "country%3A" + country[0]

        for i in range(1, len(country)):
            filter_query = filter_query + append + country[i]
            #if(i != len(country) -1)# or len(lang) > 0 or len(topic) > 0 or verified == "true"):
            #   fq = fq+append

        # if(each_query != "ptshrikant"):
        if (len(lang) > 0):
            if (filter_query == ""):
                filter_query = "fq=" + "tweet_lang%3A" + lang[0]
            else:
                filter_query = filter_query + and_append + "tweet_lang%3A" + lang[
                    0]

        #if(len(lang) > 0)
        #    fq = fq +"tweet_lang%3A"+lang[0]

            for i in range(1, len(lang)):
                filter_query = filter_query + append + lang[i]
                if (i != len(lang) -
                        1):  # or len(topic) > 0 or verified == "true"):
                    filter_query = filter_query + append

        if (len(topic) > 0):
            if (filter_query == ""):
                filter_query = "fq=" + "poi_name%3A" + topic[0]
            else:
                filter_query = filter_query + and_append + "poi_name%3A" + topic[
                    0]

        for i in range(1, len(topic)):
            filter_query = filter_query + append + topic[i]
            #if(i != len(topic) -1 or verified == "true"):
            #   fq = fq+append

        if (verified == True):
            if (filter_query == ""):
                filter_query = "fq=" + "verified%3Atrue"
            else:
                filter_query = filter_query + and_append + "verified%3Atrue"

        if (verified == False):
            if (filter_query == ""):
                filter_query = "fq=" + "verified%3Afalse"
            else:
                filter_query = filter_query + and_append + "verified%3Afalse"

        #2019-09-07T00:00:00Z TO 2019-09-08T00:00:00Z
        #tweet_date%3A%5B2019-09-07T00%3A00%3A00Z%20TO%202019-09-08T00%3A00%3A00Z%5D%20
        tweet_date_from = jsondata.get('tweetDateFrom')
        tweet_date_to = jsondata.get('tweetDateTo')

        if (tweet_date_from != ""):
            tweet_date_from = tweet_date_from + "T00:00:00Z"

        if (tweet_date_to != ""):
            tweet_date_to = tweet_date_to + "T00:00:00Z"

        if (tweet_date_from != "" and tweet_date_to != ""):
            date_filter = tweet_date_from + " TO " + tweet_date_to

            date_filter = date_filter.replace(":", "%3A")
            date_filter = date_filter.replace(" ", "%20")
            #print(date_filter)
            date_filter = "tweet_date%3A%5B" + date_filter + "%5D%20"
            #print(date_filter)
            if (filter_query == ""):
                filter_query = "fq=" + date_filter
            else:
                filter_query = filter_query + and_append + date_filter
        elif (tweet_date_from != ""):
            date_filter = tweet_date_from + " TO "

            date_filter = date_filter.replace(":", "%3A")
            date_filter = date_filter.replace(" ", "%20")
            #print(date_filter)
            date_filter = "tweet_date%3A%5B" + date_filter + "%20*%5D"
            #print(date_filter)
            if (filter_query == ""):
                filter_query = "fq=" + date_filter
            else:
                filter_query = filter_query + and_append + date_filter
        elif (tweet_date_to != ""):
            #tweet_date%3A%5B*%20TO%202019-09-08T00%3A00%3A00Z%5D
            date_filter = "TO " + tweet_date_to

            date_filter = date_filter.replace(":", "%3A")
            date_filter = date_filter.replace(" ", "%20")
            #print(date_filter)
            date_filter = "tweet_date%3A%5B*%20" + date_filter + "%5D"
            #print(date_filter)
            if (filter_query == ""):
                filter_query = "fq=" + date_filter
            else:
                filter_query = filter_query + and_append + date_filter

        # print(filter_query)
        #http://18.218.221.88:8984/solr/BM25/select?defType=edismax&q=ARTIKEL&wt=json
        #http://18.218.221.88:8984/solr/BM25/select?defType=edismax&q=Anti-Refugee%20Rally%20in%20Dresden&fl=id%2Cscore&wt=json&indent=true&rows=20
        #http://ec2-18-219-82-180.us-east-2.compute.amazonaws.com:8984/solr/IRF19P1/select?fq=tweet_date%3A%5B2019-09-07T00%3A00%3A00Z%20TO%202019-09-08T00%3A00%3A00Z%5D%20AND%20verified%3Atrue&q=*%3A*
        #tweet_date:[2019-09-07T00:00:00Z TO 2019-09-08T00:00:00Z] AND verified:true
        if (exact_match):
            inurl = 'http://' + ip + '/solr/' + IRModel + '/select?' + filter_query + '&q=' + input_query + '&rows=1000'
            # if(jsondata.get('query') == "isro"):
            #     inurl = 'http://' + ip + '/solr/' + IRModel + '/select?' + filter_query + '&q='+ input_query +'&rows=124'
        else:
            inurl = 'http://' + ip + '/solr/' + IRModel + '/select?defType=edismax&' + filter_query + '&q=' + input_query + '&rows=1000'

        print(inurl)
        data = urllib.request.urlopen(inurl)
        docs = json.load(data)['response']['docs']
        #print(docs)
        # print("length:", len(docs))

        sentiment_list = dict()
        sentiment_list['positive'] = 0
        sentiment_list['neutral'] = 0
        sentiment_list['negative'] = 0
        for tweet_texts in docs:
            sentiment = sentiment_analyse(tweet_texts['tweet_text'][0])
            tweet_texts['sentiment'] = sentiment
            sentiment_list[sentiment] = sentiment_list.get(sentiment) + 1
            # print(tweet_texts)

        # files = [f for f in os.listdir('.') if os.path.isfile(f)]
        # for f in files:
        #     print(f)

        # os.remove("Hashtags.html")
        # os.remove("Language.html")
        # os.remove("Location.html")
        # os.remove("Mentions.html")
        # os.remove("Sentiments.html")
        # os.remove("TimeSeries.html")
        # os.remove("TimeSeriesLanguage.html")
        # os.remove("Topics.html")

        # print("-----------------------------------------------------------------")
        # files = [f for f in os.listdir('.') if os.path.isfile(f)]
        # for f in files:
        #     print(f)

        date_list = list()
        lang_list = list()
        country_list = list()
        hashtags_list = list()
        mentions_list = list()
        date_lang_list = dict()
        topics = dict()

        for i in range(len(docs)):
            try:
                # date_time = docs[i].get("tweet_date")[0].find("T")
                # print(date_time)
                tweet_date = docs[i].get("tweet_date")[0][0:10]
                date_list.append(tweet_date)
                docs[i]["tweet_date"] = tweet_date
                doc_tweet_lang = docs[i].get("tweet_lang")[0]
                lang_list.append(doc_tweet_lang)
                tweet_topic = docs[i].get("topic")[0]
                if (doc_tweet_lang in date_lang_list):
                    date_lang_list[doc_tweet_lang].append(
                        docs[i].get("tweet_date")[0][0:10])
                else:
                    date_lang_list[doc_tweet_lang] = list()
                    date_lang_list[doc_tweet_lang].append(
                        docs[i].get("tweet_date")[0][0:10])
                if (tweet_topic in topics):
                    topics[tweet_topic] = topics.get(tweet_topic) + 1
                else:
                    topics[tweet_topic] = 1

                country_list.append(docs[i].get("country")[0])
                # print(country_list)
                (hashtags_list.append(docs[i].get("hashtags.text")[0])
                 if docs[i].get("hashtags.text")[0] is not None else None)
                # if(docs[i].get("hashtags")[0]):
                #     hashtags_list.append(docs[i].get("hashtags")[0])
                # print(hashtags_list)
                # if(docs[i].get("mentions")[0]):
                (mentions_list.append(docs[i].get("mentions")[0])
                 if docs[i].get("mentions")[0] is not None else None)
                # mentions_list.append(docs[i].get("mentions")[0])
                # print(mentions_list)
            except:
                pass
        # print(date_list)
        # try:
        date_list = dict(Counter(date_list))
        lang_list = dict(Counter(lang_list))
        country_list = dict(Counter(country_list))
        hashtags_list = dict(Counter(hashtags_list))
        mentions_list = dict(Counter(mentions_list))
        # print(len(mentions_list))

        for key in date_lang_list:
            date_lang_list[key] = dict(Counter(date_lang_list[key]))

        # print(date_list)
        # print(lang_list)
        # print(country_list)
        # print(hashtags_list)
        # print(mentions_list)
        # print(date_lang_list)

        country_data = {
            'country': ['United States', 'India', 'Brazil'],
            'Tweets': [
                country_list.get('USA'),
                country_list.get('India'),
                country_list.get('Brazil')
            ],
            'country code': ['USA', 'IND', 'BRA']
        }
        country_df = pd.DataFrame(country_data)

        fig = px.choropleth(country_df,
                            locations="country code",
                            color="Tweets",
                            hover_name="country",
                            color_continuous_scale='plasma')
        # pio.show(fig)
        # pio.write_html(fig, file='Location.html', default_width='370px', default_height='370px')
        fig.update_layout(
            title="Heatmap of count of tweets from different countries.")
        pio.write_html(fig, file='Location.html')

        fig = go.Figure(data=[
            go.Pie(labels=list(lang_list.keys()),
                   values=list(lang_list.values()))
        ])
        # pio.show(fig)
        # pio.write_html(fig, file='Language.html', default_width='370px', default_height='370px')
        fig.update_layout(
            title="Pie chart of count of tweets in different languages")
        pio.write_html(fig, file='Language.html')

        date_list_key_sorted = list()
        date_list_value_sorted = list()
        for i in sorted(date_list.keys()):
            date_list_key_sorted.append(i)
            date_list_value_sorted.append(date_list.get(i))
        fig = go.Figure(
            go.Scatter(x=date_list_key_sorted, y=date_list_value_sorted))
        fig.update_xaxes(title_text='Dates')
        fig.update_yaxes(title_text='No of tweets')
        fig.update_layout(title="Number of tweet on different dates")
        # pio.show(fig)
        # pio.write_html(fig, file='TimeSeries.html', default_width='370px', default_height='370px')
        pio.write_html(fig, file='TimeSeries.html')

        fig = go.Figure()
        for key in date_lang_list:
            date_lang_list_key_sorted = list()
            date_lang_list_value_sorted = list()
            for i in sorted(date_lang_list[key].keys()):
                date_lang_list_key_sorted.append(i)
                date_lang_list_value_sorted.append(date_lang_list[key].get(i))

            fig.add_trace(
                go.Scatter(
                    x=date_lang_list_key_sorted,
                    y=date_lang_list_value_sorted,
                    name=key,
                    # line_color='deepskyblue',
                    opacity=0.8))

            # print(date_lang_list_key_sorted, date_lang_list_value_sorted)
        fig.update_xaxes(title_text='Dates')
        fig.update_yaxes(title_text='No of tweets')
        # fig.update_layout(title={'text':"Number of tweet on different dates", 'xanchor': 'left'})
        fig.update_layout(
            title="Number of tweet in different languages on different dates")
        # pio.write_html(fig, file='TimeSeriesLanguage.html', default_width='370px', default_height='370px')
        pio.write_html(fig, file='TimeSeriesLanguage.html')

        # fig.add_trace(go.Scatter(
        #                 x=date_list_key_sorted_1,
        #                 y=date_list_value_sorted_1,
        #                 name="AAPL Low",
        #                 line_color='dimgray',
        #                 opacity=0.8))

        # Use date string to set xaxis range
        # fig.update_layout(xaxis_range=['2016-07-01','2016-12-31'],
        # title_text="Manually Set Date Range")
        # fig.show()

        fig = {
            "data": [{
                "type": "bar",
                "x": list(hashtags_list.keys()),
                "y": list(hashtags_list.values())
            }],
            "layout": {
                "title": {
                    "text": "Number of tweets per hashtag"
                }
            }
        }
        # fig.update_xaxes(title_text='Hashtags')
        # fig.update_yaxes(title_text='No of tweets')

        pio.show(fig)
        # pio.write_html(fig, file='Hashtags.html', default_width='370px', default_height='370px')
        pio.write_html(fig, file='Hashtags.html')

        fig = {
            "data": [{
                "type": "bar",
                "x": list(mentions_list.keys()),
                "y": list(mentions_list.values())
            }],
            "layout": {
                "title": {
                    "text": "Number of tweets per mention"
                }
            }
        }
        # fig.update_xaxes(title_text='Mention')
        # fig.update_yaxes(title_text='No of tweets')

        # pio.show(fig)
        # pio.write_html(fig, file='Mentions.html', default_width='370px', default_height='370px')
        pio.write_html(fig, file='Mentions.html')
        # print(len(list(mentions_list.keys())))
        # print(len(list(mentions_list.values())))

        fig = go.Figure(data=[
            go.Pie(labels=list(topics.keys()), values=list(topics.values()))
        ])
        # pio.show(fig)
        # pio.write_html(fig, file='Topics.html', default_width='370px', default_height='370px')
        fig.update_layout(
            title="Pie chart of count of tweets in different languages")
        pio.write_html(fig, file='Topics.html')

        fig = go.Figure(data=[
            go.Pie(labels=list(sentiment_list.keys()),
                   values=list(sentiment_list.values()))
        ])
        # pio.show(fig)
        # pio.write_html(fig, file='Language.html', default_width='370px', default_height='370px')
        fig.update_layout(
            title="Result of sentiment analysis on the query result")
        pio.write_html(fig, file='Sentiments.html')

        # except:
        # pass

        #         labels = date_list_key_sorted
        # values = date_list_value_sorted

        #print(docs[0])
        #print()
        #print(docs[1])
        #print("leng",len(docs))

        # print(country_df)
        # del country_data
        # del country_df
        return json.dumps(docs)
        id='treemap',
        figure=px.treemap(
            df,
            path=['Country', 'Axis of intervention', 'Region'],
            color="Country share % out of all budget",
            values='Voted 2018 project budget €',
            height=600,
            width=1450).update_layout(margin=dict(t=25, r=0, l=5, b=20))),
    dbc.Row([
        dbc.Col([
            dcc.Graph(id='country-map',
                      config={'displayModeBar': False},
                      figure=px.choropleth(
                          df,
                          locations="iso_alpha",
                          hover_name="Country",
                          scope='africa',
                          projection='natural earth').update_traces(
                              showlegend=False).update_layout(
                                  margin=dict(t=25, r=0, l=5, b=20)))
        ],
                width=6),
        dbc.Col([html.Div(id='container')], width=6)
    ])
],
                           fluid=True)


@app.callback(Output("treemap", "figure"), Input("year", "value"))
def build_treemap(value):
    if value == '2018':
        fig = px.treemap(
Exemplo n.º 21
0
}
region_color_dict = {
    'Northeast': 'blue',
    'South': 'red',
    'Midwest': 'yellow',
    'West': 'green',
    'Other': 'black'
}
usa_df = pd.DataFrame({'abbrev': [k for k in region_dict]})
usa_df['region'] = [region_dict[k] for k in usa_df['abbrev']]
region_map = px.choropleth(
    usa_df,
    locations=[k for k in region_dict],
    locationmode='USA-states',
    scope='usa',
    color='region',
    color_discrete_map=region_color_dict,
    category_orders={
        'region': ['Northeast', 'South', 'Midwest', 'West', 'Other']
    },
    title='Symbol outlines denote region')

# here's where the magic happens
app = dash.Dash(__name__)
app.layout = html.Div(children=[
    html.H1(children='stately.io'),
    html.Div(children="""
        Disrupting tomorrow, today!
    """),
    html.Div(children="""
        Figures may take a few seconds to display properly
def update_modal(data, year):
    # if black frame of treemap, don't update
    if data is None:
        return dash.no_update
    # if no currentpath or country is chosen, don't update
    elif data['points'][0].get('currentPath') is None:
        return dash.no_update

    elif data['points'][0]['currentPath'] == '/':
        if data['points'][0].get('label') is None:
            return dash.no_update
        else:
            label_slct = data['points'][0]['label']
            if year == '2018':
                dff = df[df["Country"] == label_slct]
            if year == '2019':
                dff = df19[df19["Country"] == label_slct]
            extract_country_index = dff[dff['Country'] ==
                                        label_slct].index.values.tolist()
            borders = [
                1 if i in extract_country_index else 4 for i in range(len(dff))
            ]

            # build map
            fig = px.choropleth(dff,
                                locations="iso_alpha",
                                hover_name="Country",
                                scope='africa',
                                projection='natural earth').update_traces(
                                    marker_line_width=borders,
                                    showlegend=False).update_layout(
                                        margin=dict(t=25, r=0, l=5, b=20))

            # create the table
            table_header = [html.Thead(html.Tr([html.Th(label_slct)]))]
            rows = []
            for x in dff["notes"]:
                if pd.isnull(x):
                    continue
                rows.append(html.Tr([html.Td(x)]))

            table_body = [html.Tbody(rows)]

            return fig, dbc.Table(table_header + table_body, bordered=True)

    # if axis of intervention is chosen (country is parent), don't update
    elif data['points'][0]['parent'] in df.Country.unique():
        label_slct = data['points'][0]['label']
        parent_slct = data['points'][0]['parent']
        if year == '2018':
            dff = df[(df["Axis of intervention"] == label_slct)
                     & (df["Country"] == parent_slct)]
        if year == '2019':
            dff = df19[(df19["Axis of intervention"] == label_slct)
                       & (df19["Country"] == parent_slct)]
            # make selected countries' borders on map thicker
        extract_country_index = dff[dff['Country'] ==
                                    parent_slct].index.values.tolist()
        borders = [
            1 if i in extract_country_index else 4 for i in range(len(dff))
        ]

        # build map
        fig = px.choropleth(dff,
                            locations="iso_alpha",
                            hover_name="Country",
                            scope='africa',
                            projection='natural earth').update_traces(
                                marker_line_width=borders,
                                showlegend=False).update_layout(
                                    margin=dict(t=25, r=0, l=5, b=20))

        # create the table
        table_header = [html.Thead(html.Tr([html.Th(label_slct)]))]
        rows = []
        for x in dff["notes"]:
            if pd.isnull(x):
                continue
            rows.append(html.Tr([html.Td(x)]))

        table_body = [html.Tbody(rows)]

        return fig, dbc.Table(table_header + table_body, bordered=True)

    # if Region is chosen, build table
    else:
        label_slct = data['points'][0]['label']
        parent_slct = data['points'][0]['parent']
        print(label_slct), print(parent_slct), print(data)
        if year == '2018':
            dff = df[(df.Region == label_slct)
                     & (df["Axis of intervention"] == parent_slct)]
        if year == '2019':
            dff = df19[(df19.Region == label_slct)
                       & (df19["Axis of intervention"] == parent_slct)]
        # make selected countries' borders on map thicker
        extract_country = data['points'][0]['currentPath']
        extract_country = extract_country.split('/')[1]
        extract_country_index = dff[dff['Country'] ==
                                    extract_country].index.values.tolist()
        borders = [
            1 if i in extract_country_index else 4 for i in range(len(dff))
        ]

        # build map
        fig = px.choropleth(dff,
                            locations="iso_alpha",
                            hover_name="Country",
                            scope='africa',
                            projection='natural earth').update_traces(
                                marker_line_width=borders,
                                showlegend=False).update_layout(
                                    margin=dict(t=25, r=0, l=5, b=20))

        # create the table
        table_header = [html.Thead(html.Tr([html.Th(label_slct)]))]
        rows = []
        for x in dff["notes"]:
            if pd.isnull(x):
                continue
            rows.append(html.Tr([html.Td(x)]))

        table_body = [html.Tbody(rows)]

        return fig, dbc.Table(table_header + table_body, bordered=True)
Exemplo n.º 23
0
# creating another map wich animates the spread of the virus
fig2 = px.scatter_geo(df,
                      locations='countryCode',
                      color='continent',
                      hover_name='country',
                      size='cases',
                      projection="natural earth",
                      title='World COVID-19 Cases Animation',
                      animation_frame="date")
# fig.show()

# creating an animated map where we can see how many people die of covid-19
fig3 = px.choropleth(df,
                     locations="countryCode",
                     color="deaths",
                     hover_name="country",
                     animation_frame="date",
                     range_color=[0, 2500])
'''
Since the data is in a time-series format, i decided to make accumulated data
so that i can show total deaths and cases.

'''
total_list = df.groupby('countryCode')['deaths'].sum().tolist()
country_list = df["countryCode"].tolist()
country_set = set(country_list)
country_list = list(country_set)
country_list.sort()

new_df = pd.DataFrame(list(zip(country_list, total_list)),
                      columns=['countryCode', 'deaths'])
Exemplo n.º 24
0
# Import plotly express library for the line graph
import plotly.express as px 

# The following code till Line 38 is the code for the line graph
grp = cases.groupby(['ObservationDate', 'Country/Region'])['Confirmed', 'Deaths', 'Recovered'].max()
grp = grp.reset_index()
grp['Date'] = pd.to_datetime(grp['ObservationDate'])
grp['Date'] = grp['Date'].dt.strftime('%m/%d/%Y')
grp['Active'] = grp['Confirmed'] - grp['Recovered'] - grp['Deaths']
grp['Country'] = grp['Country/Region']
fig = px.choropleth(grp, locations="Country", locationmode='country names',
 color="Confirmed",
 hover_name="Country/Region",
 hover_data = [grp.Recovered,grp.Deaths,grp.Active],
 projection="mercator",
 animation_frame="Date",width=1000, height=700,
 color_continuous_scale='Reds',
 range_color=[1000,50000],
 title='World Map of Coronavirus Confirmed Cases')
fig.update(layout_coloraxis_showscale=True)

# Set the variable for the us covid cases
us_covid = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv", header = 0,
dtype={"fips": str}, parse_dates=[0])

# Unique method to classify state
us_covid['state'].unique()

# Query method to define the desired states from the dataset
us_covid_ne = us_covid.query('state == ["Connecticut", "Maine", "Massachusetts", "New Hampshire", "Rhode Island", "Vermont", "New Jersey", "New York", "Pennsylvania"]')
Exemplo n.º 25
0
with urlopen(
        'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
) as response:
    counties = json.load(response)

import pandas as pd
df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
    dtype={"fips": str})

import plotly.express as px

fig = px.choropleth(df,
                    geojson=counties,
                    locations='fips',
                    color='unemp',
                    color_continuous_scale="Viridis",
                    range_color=(0, 12),
                    scope="usa",
                    labels={'unemp': 'unemployment rate'})
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

from flask import Flask, render_template, url_for
import dash
import dash_core_components as dcc
import dash_html_components as html

server = Flask(__name__)


@server.route('/')
def index():
Exemplo n.º 26
0
def fig_a002():

    # -- PHARMA
    pharma = (
        prep_salutegov.parse_dataset("pharmacies")
        .groupby("region_code")[["pharmacy_code"]]
        .nunique()
        .reset_index()
        .rename(columns={"pharmacy_code": "n_pharmacies"})
    )
    asl = (
        prep_salutegov.parse_dataset("asl_comuni_pop")
        .replace("", np.nan)
        .dropna(subset=["region_code"])
    )
    asl["TOTALE"] = (
        asl["TOTALE"]
        .str.replace(".", "")
        .str.replace(",", ".")
        .replace("", np.nan)
        .astype(float)
    )
    pop = asl.groupby(["region_code"]).agg(
        population=pd.NamedAgg("TOTALE", "sum"),
        region=pd.NamedAgg("region", "first"),
    )

    pharma["population"] = pop.reindex(pharma["region_code"].values)[
        "population"
    ].values
    pharma["region"] = (
        pop.reindex(pharma["region_code"].values)["region"].str.title().values
    )
    pharma.loc[
        pharma.region_code == "04", "region"
    ] = "Trentino-Alto Adige/Südtirol"
    pharma["hab_per_pharma"] = (
        (pharma["population"] / pharma["n_pharmacies"]).round(0).astype(int)
    )

    fig_a002 = px.choropleth(
        pharma,
        geojson=GDF_REG,
        color="hab_per_pharma",
        hover_data=["region", "n_pharmacies", "population"],
        locations="region_code",
        # range_color=(0, 3.5),
        center={"lat": 42.65, "lon": 12.4},
        featureidkey="properties.reg_istat_code",
        projection="mercator",
        template="plotly_white",
        color_continuous_scale=px.colors.diverging.Temps,
        labels={
            "region_code": "Cod. Regione",
            "region": "Regione",
            "hab_per_pharma": "Ab. per Farmacia",
            "n_pharmacies": "Numero Farmacie",
            "population": "Numero Abitanti",
        },
        # line_shape="spline",
    )
    fig_a002.update_geos(fitbounds="locations", visible=False).update_layout(
        width=600, height=600
    )

    fig_a002.update_layout(
        margin={"l": 80, "r": 140, "b": 80, "t": 100, "autoexpand": False},
        title=dict(
            text="<br><b>Abitanti per Farmacia</b></br>"
            '<span style="font-size: 11px;">Anno 2018 - Meno è Meglio</span>',
            x=0.5,
            y=0.96,
        ),
        xaxis=dict(title=None),
        yaxis_tickformat="20",
        legend=dict(orientation="h", yanchor="top", y=-0.15, title=None),
        # showlegend=False,
        annotations=[
            dict(
                text="Fonte: Rielaborazione BuildNN & Tortuga da Ministero "
                "della Salute",
                font=dict(size=9, color="grey"),
                showarrow=False,
                xref="paper",
                yref="paper",
                y=-0.0,
            )
        ],
    )

    watermark(fig_a002)

    return fig_a002
Exemplo n.º 27
0
%load_ext google.colab.data_table
import pandas as pd
url="https://raw.githubusercontent.com/marelly1/pandas/master/totalescv.csv"

import pandas as pd
url="https://raw.githubusercontent.com/marelly1/pandas/master/totalescv.csv"

df=pd.read_csv(url)
df=df.T
df=df.drop(["date"])
df=df.reset_index()
df=df.rename({"index":"Paises",53:"Total"},axis=1)
print(list(df))

#se debe instalar por el cmd de windows
#pip install pycountry

import pycountry
def get_alph_3(location):
  try:
    return pycountry.countries.get(name=location).alpha_3
  except:
    return None

df["Code"]=df["Paises"].apply(lambda x: get_alph_3(x))
print(df.head(6))

import plotly.express as px
fig = px.choropleth(df,locations="Code",color="Total",hover_name="Paises",color_continuous_scale=px.colors.sequential.Plasma)
fig.show()
Exemplo n.º 28
0
def eligible_map_func(elig_data, dose):
    fig = px.choropleth(
        elig_data,
        geojson=jdata,
        locations="id",
        color=elig_data["Procent vaccinerade"],
        # Below gives discrete colours for ranges
        color_continuous_scale=[
            (splits[0], map_colour[10]),
            (splits[1], map_colour[10]),
            (splits[1], map_colour[9]),
            (splits[2], map_colour[9]),
            (splits[2], map_colour[8]),
            (splits[3], map_colour[8]),
            (splits[3], map_colour[7]),
            (splits[4], map_colour[7]),
            (splits[4], map_colour[6]),
            (splits[5], map_colour[6]),
            (splits[5], map_colour[5]),
            (splits[6], map_colour[5]),
            (splits[6], map_colour[4]),
            (splits[7], map_colour[4]),
            (splits[7], map_colour[3]),
            (splits[8], map_colour[3]),
            (splits[8], map_colour[2]),
            (splits[9], map_colour[2]),
            (splits[9], map_colour[1]),
            (splits[10], map_colour[1]),
        ],
        # this keeps the range of colours constant regardless of data
        range_color=[0, 100],
        scope="europe",
        hover_name="Region",
        hover_data={
            "Procent vaccinerade": ":.2f",
            "Vaccinationsstatus": True,
            "id": False,
        },
        labels={
            "Procent vaccinerade":
            "Percentage of eligible<br>population vaccinated (%)",
            "Vaccinationsstatus": "<br>Number of Doses",
        },
    )
    # this section deals with the exact focus on the map
    fig.update_layout(geo=dict(
        lonaxis_range=[20, 90],  # the logitudinal range to consider
        lataxis_range=[48, 100],  # the logitudinal range to consider
        projection_scale=4.55,  # this is kind of like zoom
        center=dict(lat=lat_foc, lon=lon_foc),  # this will center on the point
        visible=False,
    ))
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    fig.update_layout(dragmode=False)
    # The below labels the colourbar categories
    fig.update_layout(
        coloraxis_colorbar=dict(
            title="<b>Percentage of eligible<br>population vaccinated with<br>"
            + dose + "</b>",
            tickvals=[5, 15, 25, 35, 45, 55, 65, 75, 85, 95],
            ticktext=[
                "00.00 - 9.99%",
                "10.00 - 19.99%",
                "20.00 - 29.99%",
                "30.00 - 39.99%",
                "40.00 - 49.99%",
                "50.00 - 59.99%",
                "60.00 - 69.99%",
                "70.00 - 79.99%",
                "80.00 - 89.99%",
                "90.00 - 100.00%",
            ],
            x=0.51,
            y=0.40,
            thicknessmode="pixels",
            thickness=10,
            lenmode="pixels",
            len=285,
        ),
        font=dict(size=12),
    )
    fig.update_traces(marker_line_color="white")
    # fig.show()
    filename = os.path.join(os.getcwd(), "vaccine_plots",
                            "{}_elig_map.json".format(name.replace(" ", "")))
    if not os.path.isdir(os.path.dirname(filename)):
        os.mkdir(os.path.dirname(filename))
    fig.write_json(filename)
Exemplo n.º 29
0
------------------------------------------------------------------------------------------------------------------------------------------------------
'''
path = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/09-07-2020.csv'

df = pd.read_csv(path)
df.drop(['FIPS', 'Admin2', 'Last_Update', 'Province_State', 'Combined_Key'],
        axis=1,
        inplace=True)
df.rename(columns={'Country_Region': "Country"}, inplace=True)
world = df.groupby("Country")['Confirmed', 'Active', 'Recovered',
                              'Deaths'].sum().reset_index()

figure = px.choropleth(world,
                       locations="Country",
                       locationmode="country names",
                       color="Confirmed",
                       hover_name="Country",
                       color_continuous_scale="tealgrn",
                       range_color=[1, 10000000],
                       title="Countries with Confirmed cases")

tabControl = ttk.Notebook(root)

tab1 = ttk.Frame(tabControl)
tabControl.add(tab1, text='CovidView')

tab2 = ttk.Frame(tabControl)
tabControl.add(tab2, text='Covid19 Map')

tab3 = ttk.Frame(tabControl)
tabControl.add(tab3, text="Advice-O-Bot")
def generate_map(df):
    df = rename(df)
    df['POS'] = df['County'] + ', ' + df['StateName']
    maps = []
    with urlopen(
            'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
    ) as response:
        counties = json.load(response)
    for key in keys:
        fig = px.choropleth(
            df,
            geojson=counties,
            locations='countyFIPS',
            color=np.log(df[key] + 1),
            color_continuous_scale=[
                '#F7E8E4', '#F5C8BB', '#B96D67', '#A83C3B', '#8B2222',
                '#5B0D0D', '#5A2318'
            ],
            scope="usa",
            hover_data=[
                'State', 'County', 'Cumulative Cases', 'New Cases',
                'Cumulative Deaths', 'New Deaths', 'Deaths per 100k',
                'Cases per 100k', 'New Cases per 100k', 'New Deaths per 100k'
            ],
            title=key + ' on ' +
            (datetime.today() - timedelta(days=1)).strftime('%m-%d'))
        fig.update_layout(coloraxis_colorbar=dict(
            len=0.75,
            title=key,
            tickvals=[
                2.302585092994046, 4.605170185988092, 6.907755278982137,
                9.210340371976184, 11.512925464970229
            ],
            ticktext=['10', '100', '1k', '10k', '100k', '1000k'],
            x=1,
            y=0.5))
        ## update the hover information
        for c in ["countyFIPS=%{location}<br>", "<br>color=%{z}"]:
            fig['data'][0]['hovertemplate'] = fig['data'][0][
                'hovertemplate'].replace(c, "")
        fig['data'][0]['hovertemplate'] = fig['data'][0][
            'hovertemplate'].replace("=", ": ")
        fig.update_layout(margin={"r": 0, "t": 40, "l": 0, "b": 0})
        fig.update_layout(
            paper_bgcolor='rgb(0,0,0)',
            plot_bgcolor='rgb(0,0,0)',
            template='plotly_dark',
        )
        fig['layout'].update(width=900, height=450, autosize=True, title_x=0.3)
        if key == 'Cumulative Cases':
            fig.write_image(oj(parentdir, "results/search_map.svg"),
                            width=900,
                            height=450)
        maps.append(
            plotly.offline.plot(fig, include_plotlyjs=False,
                                output_type='div'))

        df_tab = df.sort_values(by=key, ascending=False)
        df_tab = df_tab.reset_index(drop=True)[['POS', key]].loc[:19, :]
        fig = go.Figure(data=[
            go.Table(header=dict(values=['', 'County', key],
                                 line_color='grey',
                                 fill_color='darkgrey',
                                 font_color='white',
                                 font_size=12,
                                 align='center'),
                     cells=dict(values=[[i + 1 for i in range(len(df_tab))],
                                        df_tab['POS'], df_tab[key]],
                                line_color='darkgrey',
                                fill_color='grey',
                                font_color='white',
                                font_size=11,
                                align='center'),
                     columnwidth=[20, 120, 80])
        ])
        fig['layout'].update(paper_bgcolor='rgb(0,0,0)',
                             plot_bgcolor='rgb(0,0,0)',
                             margin=dict(l=0, r=0, t=0, b=0),
                             width=200,
                             height=550,
                             autosize=True,
                             template='plotly_dark')
        fig.write_image(oj(parentdir, "results/" + key + ".svg"),
                        width=200,
                        height=550)
    print('succesfully generated search map')
    return maps