<jupyter_start><jupyter_text>TreefortBnB Prices Data Visualization NotebookLink to data and description: https://priceonomics.com/the-priceonomics-data-puzzle-treefortbnb/<jupyter_code>import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# set plotting parameters
%matplotlib inline

plt.rcParams['figure.figsize'] = (10, 30)
plt.rcParams['xtick.labelsize'] = 16
plt.rcParams['ytick.labelsize'] = 16
plt.rcParams['axes.labelsize'] = 20
plt.rcParams['legend.fontsize'] = 20
# plt.rcParams['text.usetex'] = True
plt.rcParams.update({'axes.titlesize': '35'})
plt.style.use('fivethirtyeight')
# load dataset
df = pd.read_csv('treefortbnb_data.csv')
# clean up col names
df.columns = ['id', 'city', 'state', 'price', 'num_reviews']
df.head()
df.shape
# check for duplicates
df[df.duplicated(subset=['city', 'state', 'price', 'num_reviews'])]<jupyter_output><empty_output><jupyter_text>Because there are so many duplicate combinations of city, state, price, and reviews, I will take the unique id column at face value and assume there are not duplicates in the dataset.<jupyter_code># fix uppercase issue (e.g. miami vs. Miami)
df['city'] = df['city'].apply(lambda x: x.lower())
df['city'] = df['city'].apply(lambda x: x.lower())
# create city_state column
def clean_row(row): 
    return row['city'].title() + ', ' + row['state']

df['city_state'] = df.apply(clean_row, axis=1)
# get median list price and number of listings by city
# get prices for top 100 cities based on number of listings
df_sorted = df.groupby('city_state')['price'].agg(['median', 'count']).reset_index().sort_values(by=['count', 'median'], ascending=False)[:100].sort_values(by=['median'], ascending=False)
# create dataframe for plotting
df_sorted.columns = ['city', 'median_list_price', 'count']
df_sorted['median_list_price'] = df_sorted['median_list_price'].apply(lambda x: int(x))
# add column to dataframe for easy labeling
def tup(row):
    return (row['median_list_price'], row['count'])

df_sorted['tup'] = df_sorted.apply(tup, axis=1)
# initialize the matplotlib figure
f, ax = plt.subplots(figsize=(10, 30))

# plot the mediam prices
sns.set_color_codes('pastel')
sns.barplot(x='median_list_price', y='city', data=df_sorted[:100], label='Meidan List Price', color='b')

# add a legend and remove tick labels
ax.legend(ncol=2, loc='center right', frameon=False)
ax.set(xlim=(0, 700), ylabel='', xlabel='')
ax.get_xaxis().set_visible(False)
sns.despine(left=True, bottom=True)

# add text labels
for ix, val in enumerate(df_sorted['tup'][:100]):
    plt.text(val[0] + 4.5, ix + .25, '$'+str(val[0]), fontsize=13)
    if len(str(val[1])) > 3:
        plt.text(val[0] - 72, ix + .25, 'n = '+str(val[1]), fontsize=12.5, color='#384a85')
    elif val[0] < 100 and len(str(val[1])) == 3:
        plt.text(val[0] - 61.7, ix + .25, 'n = '+str(val[1]), fontsize=12.5, color='#384a85')
    elif val[0] < 100 and len(str(val[1])) < 3:
        plt.text(val[0] - 58, ix + .25, 'n = '+str(val[1]), fontsize=12.5, color='#384a85')
    else:
        plt.text(val[0] - 61, ix + .25, 'n = '+str(val[1]), fontsize=12.5, color='#384a85')

# add title and save output
plt.title('Highest Median TreeBnB Nightly List Prices')
plt.figtext(0.425, 0.07, 'Note: only considering cities in the top 100 for listing count\nSource: Pricenomics Data Puzzle',
            fontsize=11)
plt.savefig('treebnb.png', dpi=300, bbox_inches = 'tight')<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup