6/19/2021

Python Plot

# Import matplotlib.pyplot with alias plt

import matplotlib.pyplot as plt

# Show and clean up plot

plt.show()

plt.clf()

 

# Build histogram with 5 bins

plt.hist(life_expbins = 5)

# Create a bar plot of the number of avocados sold by size

nb_sold_by_size.plot(x="size"y="number of avacados sold",kind="bar")

# Create a line plot of the number of avocados sold by date

nb_sold_by_date.plot(x="date"y="number of avocados sold",kind="line"rot=45)

# Scatter plot of nb_sold vs avg_price with title

avocados.plot (x="nb_sold"y="avg_price"kind="scatter",title="Number of avocados sold vs. average price")

# Modify transparency to 0.5, bins to 20

avocados[avocados["type"] == "conventional"]["avg_price"].hist(alpha=0.5bins=20) 

# Add a legend

plt.legend(["conventional""organic"])

 

# Create a bar plot of the number of avocados sold by size

nb_sold_by_size.plot(x="size"y="number of avacados sold",kind="bar") 

 

# Plot only the close_dow and close_bond columns
dow_bond.plot(y=['close_dow''close_bond'], x='date'rot=90) 
 
import matplotlib.pyplot as plt
import seaborn as sns

# Set default Seaborn style
sns.set()
_=plt.hist(versicolor_petal_length)
_=plt.ylabel('versicolor_petal_length')
plt.show()


def ecdf(data):
"""Compute ECDF for a one-dimensional array of measurements."""
# Number of data points: n
n = len(data)
# x-data for the ECDF: x
x = np.sort(data)
# y-data for the ECDF: y
y = np.arange(1, n+1) / n

return x, y
 
# Compute ECDFs
x_set, y_set = ecdf(setosa_petal_length)
x_vers, y_vers = ecdf(versicolor_petal_length)
x_virg, y_virg = ecdf(virginica_petal_length)

# Plot all ECDFs on the same plot
_ = plt.plot(x_set, y_set, marker = '.', linestyle = 'none')
_ = plt.plot(x_vers, y_vers, marker = '.', linestyle = 'none')
_ = plt.plot(x_virg, y_virg, marker = '.', linestyle = 'none')

# Annotate the plot
plt.legend(('setosa', 'versicolor', 'virginica'), loc='lower right')
_ = plt.xlabel('petal length (cm)')
_ = plt.ylabel('ECDF')
 
 
# Overlay percentiles as red diamonds.
_ = plt.plot(ptiles_vers, percentiles/100, marker='D', color='red',
linestyle='none')
 
_ = sns.boxplot(x='east_west', y='dem_share', data=df_all_states)
 

# Compute bin edges: bins
bins = np.arange(0, max(n_defaults) + 2) - 0.5

# Generate histogram
_ = plt.hist(n_defaults, normed=True,bins=bins)

# Define a function called plot_timeseries
def plot_timeseries (axes, x, y, color, xlabel, ylabel):

# Plot the inputs x,y in the provided color
axes.plot(x, y, color=color)

# Set the x-axis label
axes.set_xlabel(xlabel)

# Set the y-axis label
axes.set_ylabel(ylabel, color=color)

# Set the colors tick params for y-axis
axes.tick_params ('y', colors=color)


fig, ax = plt.subplots()
# Plot the CO2 levels time-series in blue
plot_timeseries(ax, climate_change.index, climate_change.co2, 'blue', "Time (years)" , "CO2 levels")
# Create an Axes object that shares the x-axis
ax2 = ax.twinx()
# Plot the relative temperature data in red
plot_timeseries(ax2, climate_change.index, climate_change.relative_temp, 'red', "Time (years)", "Relative temp (Celsius)")
# Annotate point with relative temperature >1 degree
ax2.annotate(">1 degree", xy = (pd.Timestamp('2015-10-06'),1), xytext=(pd.Timestamp('2008-10-06'), -0.2), arrowprops={"arrowstyle":"->", "color": "gray"})

# Add bars for "Gold" with the label "Gold"
ax.bar(medals.index, medals.Gold, label="Gold")
# Stack bars for "Silver" on top with label "Silver"
ax.bar(medals.index, medals.Silver, bottom=medals.Gold, label = "Silver")
# Stack bars for "Bronze" on top of that with label "Bronze"
ax.bar(medals.index, medals.Bronze, bottom=medals.Gold+medals.Silver, label = "Bronze")
# Display the legend
ax.legend()
plt.show()

ax.hist(mens_gymnastics.Weight, label = "Gymnastics", histtype='step',bins=5)

ax.bar("Rowing", mens_rowing.Height.mean(), yerr=mens_rowing.Height.std())

ax.errorbar(seattle_weather.MONTH, seattle_weather["MLY-TAVG-NORMAL"], yerr=seattle_weather['MLY-TAVG-STDDEV'])


ax.boxplot([mens_rowing.Height, mens_gymnastics.Height])
ax.set_xticklabels(['Rowing', 'Gymnastics'])

plt.style.use('Solarize_Light2')
fig, ax = plt.subplots()

# Set fig size then Save as a PNG file with 300 dpi
fig.set_size_inches([5,3])
fig.savefig('figure_5_3.png')
fig.savefig('my_figure_300dpi.png', dpi=300)

sns.countplot(y=region)

sns.countplot(x='Spiders',data = df)

sns.countplot(x='school',data=student_data,hue='location', palette=palette_colors)

sns.scatterplot(x="absences", y="G3",
data=student_data,
hue="location",hue_order=['Rural','Urban'])

plt.margins(0.02)

sns.swarmplot(x='year', y='beak_depth', data=df)


df.boxplot('life', 'Region', rot=60)

没有评论: