def test_convenience(ax): l, = ax.plot([1, 2]) cursor = mplcursors.cursor() assert len(cursor.artists) == 1 cursor = mplcursors.cursor(ax) assert len(cursor.artists) == 1 cursor = mplcursors.cursor(l) assert len(cursor.artists) == 1 cursor = mplcursors.cursor([l]) assert len(cursor.artists) == 1
def test_misc_artists(ax): # Texts should not trigger a warning. text = ax.text(.5, .5, "foo") cursor = mplcursors.cursor(text) _process_event("__mouse_click__", ax, (.5, .5), 1) ax.cla() # Other unsupported artists should. coll = ax.fill_between([0, 1], 0, 1) cursor = mplcursors.cursor(coll) with pytest.warns(UserWarning): _process_event("__mouse_click__", ax, (.5, .5), 1)
def test_indexless_projections(): _, ax = plt.subplots(subplot_kw={"projection": "polar"}) ax.plot([1, 2], [3, 4]) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (1, 3), 1) assert len(cursor.selections) == 1 _process_event("key_press_event", ax, (.123, .456), "shift+left")
def test_highlight(ax): ax.plot([0, 1]) cursor = mplcursors.cursor(highlight=True) _process_event("__mouse_click__", ax, (.5, .5), 1) assert ax.artists == cursor.selections[0].extras != [] _process_event(*_get_remove_args(cursor.selections[0])) assert len(ax.artists) == 0
def inner(): img = ax.imshow([[0, 1], [2, 3]]) cursor = mplcursors.cursor(img) f_img = weakref.finalize(img, lambda: None) f_cursor = weakref.finalize(cursor, lambda: None) img.remove() return f_img, f_cursor
def test_line(ax): l, = ax.plot([0, .2, 1], [0, .8, 1], label="foo") cursor = mplcursors.cursor(multiple=True) # Far, far away. _process_event("__mouse_click__", ax, (0, 1), 1) assert len(cursor.selections) == len(ax.texts) == 0 # On the line. _process_event("__mouse_click__", ax, (.1, .4), 1) assert len(cursor.selections) == len(ax.texts) == 1 assert cursor.selections[0].annotation.get_text() == "foo\nx=0.1\ny=0.4" # Not removing it. _process_event("__mouse_click__", ax, (0, 1), 3) assert len(cursor.selections) == len(ax.texts) == 1 # Remove the text label; add another annotation. l.set_label(None) _process_event("__mouse_click__", ax, (.6, .9), 1) assert len(cursor.selections) == len(ax.texts) == 2 assert cursor.selections[1].annotation.get_text() == "x=0.6\ny=0.9" # Remove both of them (first removing the second one, to test # `Selection.__eq__` -- otherwise it is bypassed as `list.remove` # checks identity first). _process_event(*_get_remove_args(cursor.selections[1])) assert len(cursor.selections) == len(ax.texts) == 1 _process_event(*_get_remove_args(cursor.selections[0])) assert len(cursor.selections) == len(ax.texts) == 0 # Will project on the vertex at (.2, .8). _process_event("__mouse_click__", ax, (.2 - _eps, .8 + _eps), 1) assert len(cursor.selections) == len(ax.texts) == 1
def test_image(ax): ax.imshow(np.arange(4).reshape((2, 2))) cursor = mplcursors.cursor() # Not picking out-of-axes or of image. _process_event("__mouse_click__", ax, (-1, -1), 1) assert len(cursor.selections) == 0 ax.set(xlim=(-.5, 2.5), ylim=(-.5, 2.5)) _process_event("__mouse_click__", ax, (2, 2), 1) assert len(cursor.selections) == 0 # Annotation text includes image value. _process_event("__mouse_click__", ax, (.75, .75), 1) assert (cursor.selections[0].annotation.get_text() == "x=0.75\ny=0.75\n[3]") # Moving around. _process_event("key_press_event", ax, (.123, .456), "shift+left") assert (cursor.selections[0].annotation.get_text() == "x=0\ny=1\n[2]") _process_event("key_press_event", ax, (.123, .456), "shift+right") assert (cursor.selections[0].annotation.get_text() == "x=1\ny=1\n[3]") _process_event("key_press_event", ax, (.123, .456), "shift+up") assert (cursor.selections[0].annotation.get_text() == "x=1\ny=0\n[1]") _process_event("key_press_event", ax, (.123, .456), "shift+down") assert (cursor.selections[0].annotation.get_text() == "x=1\ny=1\n[3]")
def test_scatter(ax, plotter): plotter(ax, [[0, .5, 1], [0, .5, 1]]) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (.2, .2), 1) assert len(cursor.selections) == len(ax.texts) == 0 _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(cursor.selections) == len(ax.texts) == 1
def test_hover(ax): l1, = ax.plot([0, 1]) l2, = ax.plot([1, 2]) cursor = mplcursors.cursor(hover=True) _process_event("motion_notify_event", ax, (.5, .5)) assert cursor.selections[0].artist == l1 _process_event("motion_notify_event", ax, (.5, 1.5)) assert cursor.selections[0].artist == l2
def test_cropped_by_axes(): _, axs = plt.subplots(2) axs[0].plot([0, 0], [0, 1]) # Pan to hide the line behind the second axes. axs[0].set(xlim=(-1, 1), ylim=(1, 2)) axs[1].set(xlim=(-1, 1), ylim=(-1, 1)) cursor = mplcursors.cursor() _process_event("__mouse_click__", axs[1], (0, 0), 1) assert len(cursor.selections) == 0
def test_remove(ax): ax.plot([0, 1]) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(cursor.selections) == len(ax.texts) == 1 cursor.remove() assert len(cursor.selections) == len(ax.texts) == 0 _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(cursor.selections) == len(ax.texts) == 0
def test_invalid_args(): pytest.raises(ValueError, mplcursors.cursor, multiple=True, hover=True) pytest.raises(ValueError, mplcursors.cursor, bindings={"foo": 42}) pytest.raises(ValueError, mplcursors.cursor, bindings={"select": 1, "deselect": 1}) pytest.raises(ValueError, mplcursors.cursor().connect, "foo")
def plot_sounding(date, station): p, T, Td, u, v, windspeed = get_sounding_data(date, station) lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0]) lfc_pressure, lfc_temperature = mpcalc.lfc(p, T, Td) parcel_path = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC') # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(8, 8)) skew = SkewT(fig) # Plot the data temperature_line, = skew.plot(p, T, color='tab:red') dewpoint_line, = skew.plot(p, Td, color='blue') cursor = mplcursors.cursor([temperature_line, dewpoint_line]) # Plot thermodynamic parameters and parcel path skew.plot(p, parcel_path, color='black') if lcl_pressure: skew.ax.axhline(lcl_pressure, color='black') if lfc_pressure: skew.ax.axhline(lfc_pressure, color='0.7') # Add the relevant special lines skew.ax.axvline(0, color='c', linestyle='--', linewidth=2) skew.plot_dry_adiabats() skew.plot_moist_adiabats() skew.plot_mixing_lines() # Shade areas representing CAPE and CIN skew.shade_cin(p, T, parcel_path) skew.shade_cape(p, T, parcel_path) # Add wind barbs skew.plot_barbs(p, u, v) # Add an axes to the plot ax_hod = inset_axes(skew.ax, '30%', '30%', loc=1, borderpad=3) # Plot the hodograph h = Hodograph(ax_hod, component_range=100.) # Grid the hodograph h.add_grid(increment=20) # Plot the data on the hodograph mask = (p >= 100 * units.mbar) h.plot_colormapped(u[mask], v[mask], windspeed[mask]) # Plot a line colored by wind speed # Set some sensible axis limits skew.ax.set_ylim(1000, 100) skew.ax.set_xlim(-40, 60) return fig, skew
def test_line_single_point(ax): for ls in ["-", "o"]: ax.cla() ax.plot(0, ls) ax.set(xlim=(-1, 1), ylim=(-1, 1)) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (_eps, _eps), 1) assert len(cursor.selections) == len(ax.texts) == (ls == "o") if cursor.selections: assert_array_equal(np.asarray(cursor.selections[0].target), (0, 0)) cursor.remove()
def test_steps_post(ax): ax.plot([0, 1], [0, 1], drawstyle="steps-post") ax.set(xlim=(-1, 2), ylim=(-1, 2)) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (0, 1), 1) assert len(cursor.selections) == 0 _process_event("__mouse_click__", ax, (.5, 0), 1) index = cursor.selections[0].target.index assert_allclose((index.int, index.x, index.y), (0, .5, 0)) _process_event("__mouse_click__", ax, (1, .5), 1) index = cursor.selections[0].target.index assert_allclose((index.int, index.x, index.y), (0, 1, .5))
def test_callback(ax): ax.plot([0, 1]) calls = [] cursor = mplcursors.cursor() @cursor.connect("add") def on_add(sel): calls.append(sel) _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(calls) == 1 cursor.disconnect(on_add) _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(calls) == 1
def test_move(ax): ax.plot([0, 1], [0, 1]) cursor = mplcursors.cursor() # Nothing happens with no cursor. _process_event("key_press_event", ax, (.123, .456), "shift+left") assert len(cursor.selections) == 0 # Now we move the cursor left or right. _process_event("__mouse_click__", ax, (.5, .5), 1) assert tuple(cursor.selections[0].target) == (.5, .5) _process_event("key_press_event", ax, (.123, .456), "shift+left") assert tuple(cursor.selections[0].target) == (0, 0) assert cursor.selections[0].target.index == 0 _process_event("key_press_event", ax, (.123, .456), "shift+right") assert tuple(cursor.selections[0].target) == (1, 1) assert cursor.selections[0].target.index == 1
def main(): fig, axes = plt.subplots(ncols=2) num = 5 xy = np.random.random((num, 2)) lines = [] for i in range(num): line, = axes[0].plot((i + 1) * np.arange(10)) lines.append(line) points = [] for x, y in xy: point, = axes[1].plot([x], [y], linestyle='none', marker='o') points.append(point) cursor = mplcursors.cursor(points + lines, highlight=True) pairs = {**dict(zip(points, lines)), **dict(zip(lines, points))} @cursor.connect("add") def on_add(sel): sel.extras.append(cursor.add_highlight(pairs[sel.artist])) plt.show()
def test_keys(ax): ax.plot([0, 1]) cursor = mplcursors.cursor(multiple=True) _process_event("__mouse_click__", ax, (.3, .3), 1) # Toggle visibility. _process_event("key_press_event", ax, (.123, .456), "d") assert not cursor.selections[0].annotation.get_visible() _process_event("key_press_event", ax, (.123, .456), "d") assert cursor.selections[0].annotation.get_visible() # Disable the cursor. _process_event("key_press_event", ax, (.123, .456), "t") assert not cursor.enabled # (Adding becomes inactive.) _process_event("__mouse_click__", ax, (.6, .6), 1) assert len(cursor.selections) == 1 # (Removing becomes inactive.) ax.figure.canvas.draw() _process_event(*_get_remove_args(cursor.selections[0])) assert len(cursor.selections) == 1 # Reenable it. _process_event("key_press_event", ax, (.123, .456), "t") assert cursor.enabled _process_event(*_get_remove_args(cursor.selections[0])) assert len(cursor.selections) == 0
def test_multiple_figures(ax): ax1 = ax _, ax2 = plt.subplots() ax1.plot([0, 1]) ax2.plot([0, 1]) cursor = mplcursors.cursor([ax1, ax2], multiple=True) # Add something on the first axes. _process_event("__mouse_click__", ax1, (.5, .5), 1) assert len(cursor.selections) == 1 assert len(ax1.texts) == 1 assert len(ax2.texts) == 0 # Right-clicking on the second axis doesn't remove it. remove_args = list(_get_remove_args(cursor.selections[0])) remove_args[remove_args.index(ax1)] = ax2 _process_event(*remove_args) assert len(cursor.selections) == 1 assert len(ax1.texts) == 1 assert len(ax2.texts) == 0 # Remove it, add something on the second. _process_event(*_get_remove_args(cursor.selections[0])) _process_event("__mouse_click__", ax2, (.5, .5), 1) assert len(cursor.selections) == 1 assert len(ax1.texts) == 0 assert len(ax2.texts) == 1
def test_nan(ax): ax.plot([0, 1, np.nan, 3, 4]) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(cursor.selections) == len(ax.texts) == 1 assert_allclose(np.asarray(cursor.selections[0].target), (.5, .5))
"""A very basic example of mplcursor's functionalities. """ import matplotlib.pyplot as plt import numpy as np import mplcursors data = np.outer(range(10), range(1, 5)) fig, ax = plt.subplots() lines = ax.plot(data) ax.set_title("Click somewhere on a line\nRight-click to deselect\n" "Annotations can be dragged.") fig.tight_layout() mplcursors.cursor(lines) plt.show()
print(n_colors) fig, ax = plt.subplots(figsize=(10,10)) sc = plt.scatter( lower_dim_data[:,0], lower_dim_data[:,1], c=query_df["label_idx"].tolist(), cmap=cmap, s=1 ) # cursor crs = mplcursors.cursor(ax,hover=True) crs.connect( "add", lambda sel: sel.annotation.set_text( f"{word_list[sel.target.index]}\n{all_labels[sel.target.index]}" )) # colorbar c_ticks = np.arange(n_colors) * (n_colors / (n_colors + 1)) + (2 / n_colors) cbar = plt.colorbar(sc, ticks=c_ticks) #cbar = plt.colorbar() ticklabs = cbar.ax.get_yticklabels() cbar.ax.set_yticklabels(labels, ha="right") cbar.ax.yaxis.set_tick_params(pad=40)
x.annotate("", xy=(21, 1.3), xycoords='data', xytext=(10, 25), textcoords='offset points', arrowprops=dict(color="tab:red", arrowstyle="fancy")) """ x.plot(latencies) fname = '%s.experiment%02d.pdf' % (exename, idx + 1) figi.savefig(fname, bbox_inches='tight', pad_inches=0) fname = '%s.experiment%02d.svg' % (exename, idx + 1) figi.savefig(fname, bbox_inches='tight', pad_inches=0) if interactive: #cursor = mplcursors.cursor(hover=True) cursor = mplcursors.cursor(axi) @cursor.connect("add") def on_add(sel): print(sel) x, _ = sel.target x = int(round(x)) _, inst_pc, inst_full = attacks[idx][x] sel.annotation.set(text="%d: %04X (%s)" % (x, inst_pc, inst_full)) """ if idx == (len(attacks)-1): figi.show() else: figi.show() """
import json import matplotlib.pyplot as plt import mplcursors import numpy as np with open("emotion-data.json") as f: data = json.load(f) songs = [] joy = [] sadness = [] for song in data: songs.append(song) sadness.append(data[song]["sadness"] * 100) joy.append(data[song]["joy"] * 100) for i in range(len(songs)): print(songs[i] + ": (" + str(joy[i]) + ", " + str(sadness[i]) + ")") plt.xlabel("Joy") plt.ylabel("Sadness") plt.scatter(joy, sadness) mplcursors.cursor(hover=True) plt.show()
webUrl = urllib.request.urlopen( 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson' ) data = json.loads(webUrl.read()) quakes = [] quakex = [] quakey = [] quakez = [] labels = [] distanceFromEarthquake = 17 for i in data['features']: firstEarthquake = (40.751, -112.078) second = (i['geometry']['coordinates'][1], i['geometry']['coordinates'][0]) if geodesic(firstEarthquake, second).miles < distanceFromEarthquake: labelAppend = f"Magnitude: {i['properties']['mag']}" labelAppend = labelAppend + f'\n Date: {datetime.fromtimestamp(i["properties"]["time"]/1000.0).strftime("%m/%d/%Y, %H:%M:%S")}' labelAppend = labelAppend + f"\n Depth: {i['geometry']['coordinates'][2]}" labels.append(labelAppend) quakex.append(datetime.fromtimestamp(i['properties']['time'] / 1000.0)) quakey.append(i['geometry']['coordinates'][2]) quakez.append(i['properties']['mag'] * 10) quakes.append(i) plt.scatter(quakex, quakey, s=quakez) plt.ylabel('Depth') plt.xlabel('Time') mplcursors.cursor(hover=True).connect( "add", lambda sel: sel.annotation.set_text(labels[sel.target.index])) plt.show()
def test_container(ax): ax.bar(range(3), [1] * 3) assert len(mplcursors.cursor().artists) == 3
"""An example of highlighting cursors. """ import numpy as np import matplotlib.pyplot as plt import mplcursors x = np.linspace(0, 10, 100) fig, ax = plt.subplots() # Plot a series of lines with increasing slopes... lines = [] for i in range(1, 20): line, = ax.plot(x, i * x, label='$y = {}x$'.format(i)) lines.append(line) mplcursors.cursor(lines, highlight=True) plt.show()
import numpy as np import matplotlib.pyplot as plt import mplcursors x, y, z = np.random.random((3, 10)) fig, axs = plt.subplots(2) axs[0].scatter(x, y, c=z, s=100*np.random.random(10)) axs[1].plot(x, y, "o") mplcursors.cursor() plt.show()
def display(self): mplcursors.cursor() plt.gcf().autofmt_xdate() plt.legend() plt.show()
# isolation forest anomaly detection with contamination as 3% anomaly=error[error>0.02] Total_anomaly=data[anomaly==error] from sklearn.ensemble import IsolationForest clf=IsolationForest(n_estimators=100,contamination=0.003) a_train,a_test=train_test_split(error,test_size=0.3) d=clf.fit(a_train) ano=d.predict(error) iso_ano_1=data[ano==-1] iso_ano=error[ano==-1] plt.scatter(iso_ano_1.index,iso_ano,marker='o',color='red') plt.legend(['reconst error','Anomaly']) mplcursors.cursor() #%% from scipy import stats stats.ttest_ind(n_pred_test,X_test) import random random.sample(list(np.arange(0,100)),10) a=np.linspace(0,984,10) int(a) t_s=stats.ttest_ind(faulty[:-100],faulty_pred[:-100])
i=3 j=0 k="week " while i<=Num_cols: fig,ax = plt.subplots(figsize = (15,15)) street_map.plot(ax=ax,color='white') geo_df[geo_df[chr(ord('a')+j)]<=50].plot(ax=ax,markersize=20,color='white',marker='o',label='Normal') geo_df[(geo_df[chr(ord('a')+j)]>50) & (geo_df[chr(ord('a')+j)]<=80)].plot(ax=ax,markersize=15,color='#D6E2FF',marker='o',label="low") geo_df[(geo_df[chr(ord('a')+j)]>80) & (geo_df[chr(ord('a')+j)]<=100)].plot(ax=ax,markersize=15,color='#B5C9FF',marker='o',label="low") geo_df[(geo_df[chr(ord('a')+j)]>100) & (geo_df[chr(ord('a')+j)]<=120)].plot(ax=ax,markersize=15,color='#7F96FF',marker='o',label="Average") geo_df[(geo_df[chr(ord('a')+j)]>120) & (geo_df[chr(ord('a')+j)]<=140)].plot(ax=ax,markersize=15,color='#7285F8',marker='o',label='Average') geo_df[(geo_df[chr(ord('a')+j)]>140) & (geo_df[chr(ord('a')+j)]<=160)].plot(ax=ax,markersize=15,color='#009E1E',marker='o',label='Average') geo_df[(geo_df[chr(ord('a')+j)]>160) & (geo_df[chr(ord('a')+j)]<=180)].plot(ax=ax,markersize=15,color='#3CBC3D',marker='o',label='high') geo_df[(geo_df[chr(ord('a')+j)]>180) & (geo_df[chr(ord('a')+j)]<=200)].plot(ax=ax,markersize=15,color='#B9F96E',marker='o',label='high') geo_df[(geo_df[chr(ord('a')+j)]>200) & (geo_df[chr(ord('a')+j)]<=220)].plot(ax=ax,markersize=15,color='#FFF913',marker='o',label='high') geo_df[(geo_df[chr(ord('a')+j)]>220) & (geo_df[chr(ord('a')+j)]<=240)].plot(ax=ax,markersize=15,color='#E50000',marker='o',label='very High') geo_df[(geo_df[chr(ord('a')+j)]>240) & (geo_df[chr(ord('a')+j)]<=260)].plot(ax=ax,markersize=15,color='#BD0000',marker='o',label='very high') geo_df[geo_df[chr(ord('a')+j)]>260].plot(ax=ax,markersize=15,color='#000000',marker='o',label='Normal') font = {'family' : 'normal', 'weight' : 'bold', 'size' : 22,} matplotlib.rc('font', **font) i=i+1 j=j+1 plt.text(90, 35,k+str(j)) #plt.figimage(35,20,"D:\photos\Ne\dnt touch\Aura Note 4G_20170422_145225.jpg") mplcursors.cursor(hover=True).connect( "add", lambda sel: sel.annotation.set_text(sel.artist.get_label()))
def make_interactive(multiple: bool = True) -> None: """Enable interaction with the current Matplotlib figure.""" mplcursors.cursor(multiple=multiple)
def wrapper(self, *args, filepath=None, axis=None, output=None, img_format=None, always_save=False, colors: TypedList[str]=None, linestyles: TypedList[str]=None, markers: TypedList[str]=None, rc_params=None, **kwargs): def is_f_param(param): """ Return True if the parameter is for `f`, False if it is for setup_plot() """ try: desc = inspect.signature(f).parameters[param] except KeyError: return False else: # Passing kwargs=42 to a function taking **kwargs # should not return True here, as we only consider # explicitly listed arguments return desc.kind not in ( inspect.Parameter.VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL, ) # Factor the *args inside the **kwargs by binding them to the # user-facing signature, which is the one of the wrapper. kwargs.update( inspect.signature(wrapper).bind_partial(self, *args).arguments ) f_kwargs = { param: val for param, val in kwargs.items() if is_f_param(param) } img_format = img_format or guess_format(filepath) or 'png' local_fig = axis is None # When we create the figure ourselves, always save the plot to # the default location if local_fig and filepath is None and always_save: filepath = self.get_default_plot_path( img_format=img_format, plot_name=f.__name__, ) cyclers = dict( color=colors, linestyle=linestyles, marker=markers, ) cyclers = { name: value for name, value in cyclers.items() if value } if cyclers: cyclers = [ make_cycler(**{name: value}) for name, value in cyclers.items() ] set_cycler = lambda axis: cls.set_axis_cycler(axis, *cyclers) else: set_cycler = lambda axis: nullcontext() if rc_params: set_rc_params = lambda axis: cls.set_axis_rc_params(axis, rc_params) else: set_rc_params = lambda axis: nullcontext() # Allow returning an axis directly, or just update a given axis if return_axis: # In that case, the function takes all the kwargs with set_cycler(axis), set_rc_params(axis): axis = f(**kwargs, axis=axis) else: if local_fig: setup_plot_kwargs = { param: val for param, val in kwargs.items() if param not in f_kwargs } fig, axis = self.setup_plot(**setup_plot_kwargs) f_kwargs.update( axis=axis, local_fig=f_kwargs.get('local_fig', local_fig), ) with set_cycler(axis), set_rc_params(axis): f(**f_kwargs) if isinstance(axis, numpy.ndarray): fig = axis[0].get_figure() else: fig = axis.get_figure() def resolve_formatter(fmt): format_map = { 'rst': cls._get_rst_content, 'html': cls._get_html, } try: return format_map[fmt] except KeyError: raise ValueError(f'Unsupported format: {fmt}') if output is None: out = axis # Show the LISA figure toolbar if is_running_ipython(): # Make sure we only add one button per figure try: toolbar = self._get_fig_data(fig, 'toolbar') except KeyError: toolbar = self._make_fig_toolbar(fig) self._set_fig_data(fig, 'toolbar', toolbar) display(toolbar) mplcursors.cursor(fig) else: out = resolve_formatter(output)(f, [], f_kwargs, axis) if filepath: if img_format in ('html', 'rst'): content = resolve_formatter(img_format)(f, [], f_kwargs, axis) with open(filepath, 'wt', encoding='utf-8') as fd: fd.write(content) else: fig.savefig(filepath, format=img_format, bbox_inches='tight') return out
def test_misc_artists_highlight(ax): # Unsupported artists trigger a warning upon a highlighting attempt. ax.imshow([[0, 1], [2, 3]]) cursor = mplcursors.cursor(highlight=True) with pytest.warns(UserWarning): _process_event("__mouse_click__", ax, (.5, .5), 1)
def test_linecollection(ax): ax.eventplot([0, 1]) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (0, 1), 1) assert_allclose(cursor.selections[0].target.index, (0, .5))
# FIXME no CS support. import numpy as np import matplotlib.pyplot as plt import mplcursors fig, ax = plt.subplots() cf = ax.contour(np.random.random((10,10))) # For contours, you'll have to explicitly specify the ContourSet ("cf", in this # case) for the z-values to be displayed. Filled contours aren't properly # supported, as they only fire a pick even when their edges are selected. mplcursors.cursor(cf) plt.show()
def test_repeated_point(ax): ax.plot([0, 1, 1, 2], [0, 1, 1, 2]) cursor = mplcursors.cursor() with pytest.warns(None) as record: _process_event("__mouse_click__", ax, (.5, .5), 1) assert not _internal_warnings(record)
fig, ax = plt.subplots() plot = ax.plot(years, rates, color="#0000FF", label="Rates", linewidth=3) ax.fill_between(years, min(movies_df["Rating"]), rates, color="yellow", alpha=0.1) # setting the label ax.set_xlabel("Years", fontsize=18) ax.set_ylabel("Rates", fontsize=18) ax.set_title("IMDB Top 250 Movie Rates Over Years", fontsize=22) # adding some hover functionality to the plot cursor = mplcursors.cursor(plot, hover=True) cursor.connect( "add", lambda sel: sel.annotation.set_text( f"{names[int(sel.target.index)]}\n{rates[int(sel.target.index)]}")) # formatting the plot fig.autofmt_xdate() plt.tight_layout() plt.legend(loc="upper left") # dataframe methods df = movies_df print(df.head()) print(df.count(0)) # print(df.set_index(["Title","Rating"]).count(level="Rating"))
result = cursor.fetchall() #print(result, flush=True) finally: connection.close() fantasy_points = [] salaries = [] for player in result: fantasy_points.append(player['fantasy_points']) salaries.append(player['salary']) fig, ax = plt.subplots() plt.scatter(fantasy_points, salaries, color='g') plt.xlabel('Fantasy Score') plt.ylabel('Salary') a, b = year.split('-') plt.title( 'Salary vs. Fantasy Score in the 20{}-20{} Basketball Season'.format( a, b)) mcur.cursor(hover=True).connect( "add", lambda sel: sel.annotation.set_text(result[sel.target.index][ 'full_name'])) plt.show()
""" Highlighting the artist upon selection ====================================== Just pass ``highlight=True`` to `cursor`. """ import numpy as np import matplotlib.pyplot as plt import mplcursors x = np.linspace(0, 10, 100) fig, ax = plt.subplots() # Plot a series of lines with increasing slopes. lines = [] for i in range(1, 20): line, = ax.plot(x, i * x, label=f"$y = {i}x$") lines.append(line) mplcursors.cursor(lines, highlight=True) plt.show()
""" import matplotlib.pyplot as plt import numpy as np import mplcursors fig, axes = plt.subplots(ncols=2) left_artist = axes[0].plot(range(11)) axes[0].set(title="No box, different position", aspect=1) right_artist = axes[1].imshow(np.arange(100).reshape(10, 10)) axes[1].set(title="Fancy white background") # Make the text pop up "underneath" the line and remove the box... c1 = mplcursors.cursor(left_artist) @c1.connect("add") def _(sel): sel.annotation.set(position=(15, -15)) # Note: Needs to be set separately due to matplotlib/matplotlib#8956. sel.annotation.set_bbox(None) # Make the box have a white background with a fancier connecting arrow c2 = mplcursors.cursor(right_artist) @c2.connect("add") def _(sel):
def test_no_duplicate(ax): ax.plot([0, 1]) cursor = mplcursors.cursor(multiple=True) _process_event("__mouse_click__", ax, (.5, .5), 1) _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(cursor.selections) == 1
def grafs(self): sig_sequence, modulsig, Fourier_m, Fourier_db, fr = self.caller() # Построение графиков fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=4, ncols=1, figsize=(12, 8), dpi=100) plt.subplots_adjust(hspace=0.7, top=0.95) # Чистый сигнал ax1.plot(self.tt, self.sig) ax1.set_title('Чистый сигнал ') ax1.set_xlabel('Время в секундах') ax1.set_ylabel('Значения сигнала') ax1.axis([0, 0.000005, -1, 1]) # последовательность ax2.plot(self.tt, sig_sequence) ax2.axis([0, 0.000005, -1.2, 1.2]) # модулированный сигнал ax2.plot(self.tt, modulsig) ax2.set_title('Модулированный сигнал ') ax2.set_xlabel('Время в секундах') ax2.set_ylabel('Значения сигнала') ax2.axis([0, 0.000005, -1.2, 1.2]) # нормированный спектр ax3.plot(fr, Fourier_m / max(Fourier_m)) ax3.set_title('Нормированный спектр ') ax3.set_xlabel('Частота в Гц') ax3.set_ylabel('Амплитуда') ax3.axis([3 * pow(10, 6), 7 * pow(10, 6), 0, 1]) # нормированный спектр в dB spectr = ax4.plot(fr, Fourier_db - max(Fourier_db)) ax4.set_title('Нормированный спектр в dB ') ax4.set_xlabel('Частота в Гц') ax4.set_ylabel('Мощность в dB') ax4.axis([3 * pow(10, 6), 7 * pow(10, 6), -50, 0]) mplcursors.cursor(spectr) # красная линия по уровню 13,6 дБ line = ax4.plot(range(3 * pow(10, 6), 7 * pow(10, 6)), -np.ones(len(range(3 * pow(10, 6), \ 7 * pow(10, 6)))) - 12.6, c='red') # очень криво ax4.axis([3 * pow(10, 6), 7 * pow(10, 6), -50, 0]) mplcursors.cursor(line) plt.show()
def process(airline): print("started " + airline) airlineFound = False dates = [] fatalities = [] dates_aggregate = [] fatalities_aggregate = [] with open('data/planecrashinfo.csv') as csvFile: dr = csv.DictReader(csvFile) for row in dr: fatalities_rev = row['fatalities'][:row['fatalities'].index(' ')] if airline in row['operator']: airlineFound = True dates.append(row['date'][row['date'].index(', ') + 2:len(row['date'])]) if '?' not in fatalities_rev: fatalities.append(int(float(fatalities_rev))) else: fatalities.append(0) else: dates.append(row['date'][row['date'].index(', ') + 2:len(row['date'])]) fatalities.append(0) if '?' not in fatalities_rev: dates_aggregate.append(row['date'][row['date'].index(', ') + 2:len(row['date'])]) fatalities_aggregate.append(int(float(fatalities_rev))) if airlineFound: dates_clean = convertToInt(remDup(dates)) dates_aggregate_clean = convertToInt(remDup(dates_aggregate)) fatalities_clean = [] fatalities_average = [] #aggregate data i = 0 for year in dates_aggregate_clean: fat_avg = 0 count = 1 for dt in dates_aggregate: if str(year) in dt: fat_avg += fatalities_aggregate[i] i += 1 count += 1 #print(fat_avg) fatalities_average.append(fat_avg / count) #airline data i = 0 #print(len(fatalities)) for year in dates_clean: fat = 0 for dt in dates: if str(year) in dt: fat += fatalities[i] i += 1 fatalities_clean.append(fat) #print("stats:") #print("first year:"+str(dates_clean[0])) #print("last year:"+str(dates_clean[len(dates_clean)-1])) #print("Highest Fatality/year:"+str(max(fatalities_clean))) lines = plt.plot(dates_clean, fatalities_clean, 'r', dates_aggregate_clean, fatalities_average, 'g') plt.axis([ dates_clean[0], dates_clean[len(dates_clean) - 1], 0, max(fatalities_clean) + 50 ]) plt.ylabel('Fatalities/year') plt.xlabel('Year') plt.title( airline + ' crashes over its history compared with the average crashes per year' ) plt.legend([airline + ' fatalities', 'Overall Average']) plt.gcf().set_size_inches(14.5, 10.5) mplcursors.cursor(lines, hover=True) plt.savefig('data/plots/' + slugify(airline) + '.png') #plt.show(lines) plt.gcf().clear() print("finished" + airline) else: print("Whoops! Airline not Found!") print( "This means that the airline has never had a fatal accident or crash, or doesn't exist in our database." )
from matplotlib import pyplot as plt import mplcursors from pandas import DataFrame import pickle import numpy as np with open('../ApartmentPrice/Analysis_Prediction_Python/prets_pvols.bin', 'rb') as f: pick = pickle.load(f) point=plt.scatter('pvols','prets',data=pick,c=pick.index ,marker='o') point plt.grid(True) plt.xlabel('expected volatility') plt.ylabel('expected return') plt.colorbar(label='Sharpe ratio') mplcursors.cursor(point) plt.show()
def plot_all_distance_gradient(dist_patient,dist_rub,dist_wash,\ grad_patient,grad_rub,grad_wash,\ LPF_patient,LPF_rub,LPF_wash,\ LPF_G_patient,LPF_G_rub,LPF_G_wash): #It plot distances and gradients (including LPF) plt.subplots_adjust(wspace=0.4,hspace=0.4) plt.figure(1) plt.subplot(2,2,1) line1 = plt.plot(dist_patient) line4 = plt.plot(grad_patient) line7 = plt.plot(LPF_patient) line10 = plt.plot(LPF_G_patient) plt.title("Self_2_Patient") plt.xlabel("Data sequence") plt.legend(['distance','gradient','LPF_Dist','LPF_Grad']) plt.grid() plt.subplot(2,2,2) line2 = plt.plot(dist_rub) line5 = plt.plot(grad_rub) line8 = plt.plot(LPF_rub) line11 = plt.plot(LPF_G_rub) plt.title("Self_2_Hand Rub") plt.xlabel("Data sequence") plt.legend(['distance','gradient','LPF_Dist','LPF_Grad']) plt.grid() plt.subplot(2,2,3) line3 = plt.plot(dist_wash) line6 = plt.plot(grad_wash) line9 = plt.plot(LPF_wash) line12 = plt.plot(LPF_G_wash) plt.title("Self_2_Wash Bin") plt.xlabel("Data sequence") plt.legend(['distance','gradient','LPF_Dist','LPF_Grad']) plt.grid() #Interative marker on graph mplcursors.cursor(line1) mplcursors.cursor(line2) mplcursors.cursor(line3) mplcursors.cursor(line4) mplcursors.cursor(line5) mplcursors.cursor(line6) mplcursors.cursor(line7) mplcursors.cursor(line8) mplcursors.cursor(line9) mplcursors.cursor(line10) mplcursors.cursor(line11) mplcursors.cursor(line12)
def test_scatter_text(ax): ax.scatter([0, 1], [0, 1], c=[2, 3]) cursor = mplcursors.cursor() _process_event("__mouse_click__", ax, (0, 0), 1) assert _parse_annotation( cursor.selections[0], "x=(.*)\ny=(.*)\n\[(.*)\]") == (0, 0, 2)
def test_removed_artist(ax): l, = ax.plot([0, 1]) cursor = mplcursors.cursor() l.remove() _process_event("__mouse_click__", ax, (.5, .5), 1) assert len(cursor.selections) == len(ax.texts) == 0
def graphingWindow(): graphing = Toplevel(master) graphing.title("Let us graph!") def allowedDeadDrives(loadedDrives, years_since): if years_since == 1: num_drives = loadedDrives * .05 num_drives = round(num_drives) if years_since == 2: num_drives = loadedDrives * .08 num_drives = round(num_drives) if years_since == 3: num_drives = loadedDrives * .1 num_drives = round(num_drives) if years_since == 4: num_drives = loadedDrives * .2 num_drives = round(num_drives) return (num_drives) # This will import the CSV to read and will ignore any rows that have no data test = pd.read_csv("/directory/for/file.csv") test = test.dropna() # This will separate out the library that had the bad disk and the disk that went bad Library = test.Library Disk = test.Replaced # This will take the separated sections and turn them into arrays Library = np.array(Library) Disk = np.array(Disk) # This builds an array with both the library and disk that failed. It makes it so it is 50 rows and 2 columns instead # of 50 columns and 2 rows TestArray = np.concatenate((Library, Disk)) TestArray = np.array_split(TestArray, 2) TestArray = np.transpose(TestArray) # This takes the array previously created and makes a turple new_array = [tuple(row) for row in TestArray] # This will go through and get the unique values including a count for how many times each value appears unique = np.unique(new_array, axis=0, return_counts=True) # This takes the unique counts and turns it into an array counting = unique[1:2:1] counting = np.transpose(counting) counting = np.array(counting) # Do this for counting number of rows needed for first part of the final array increment = 0 for x in counting: increment = increment + 1 # This will get the unique combinations of disk libraries and disks who failed library = unique[0:1:1] # This builds that array to use library = np.transpose(library) library = np.array_split(library, 1) library = np.array(library).reshape(2, increment) library = np.transpose(library) # This creates a single array that lists the unique library and disk failures and associates it with the number of # times a particular slot has failed and then sorts by the disk that failed instead of the array concat = np.column_stack((library, counting)) concat = concat[concat[:, 1].argsort()] # This gets the variable for the size of the dot placed on the chart number_of_disks = concat[:, 2] number_of_disks = np.transpose(number_of_disks) number_of_disks = number_of_disks.astype(int) # This generates the x-axis library_name = concat[:, 0] library_name = np.transpose(library_name) # This generates the y-axis disk_number = concat[:, 1] disk_number = np.transpose(disk_number) sizevalues1 = [(x + 2)**3 for x in number_of_disks] # This is for charting number of disks for each library a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 i = 0 count = 0 # Use this to determine how old the disk library is curr_date = datetime.date(datetime.now()) # This builds the number of drive replaced for each disk library as well as the maximum number allowed # Allowed number per report on https://www.backblaze.com/blog/how-long-do-disk-drives-last/ for x in Library: if x == "dev1": a = a + 1 inst_date = date(2017, 5, 12) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name1 = x num_drives1 = allowedDeadDrives(loadedDrives, years_since) if x == "dev02": b = b + 1 inst_date = date(2017, 5, 19) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name2 = x num_drives2 = allowedDeadDrives(loadedDrives, years_since) if x == "dev03": c = c + 1 inst_date = date(2017, 5, 12) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name3 = x num_drives3 = allowedDeadDrives(loadedDrives, years_since) if x == "dev04": d = d + 1 inst_date = date(2017, 5, 19) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name4 = x num_drives4 = allowedDeadDrives(loadedDrives, years_since) if x == "dev05": e = e + 1 inst_date = date(2018, 3, 18) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name5 = x num_drives5 = allowedDeadDrives(loadedDrives, years_since) if x == "dev06": f = f + 1 inst_date = date(2019, 3, 25) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name6 = x num_drives6 = allowedDeadDrives(loadedDrives, years_since) if x == "dev07": g = g + 1 inst_date = date(2018, 3, 20) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name7 = x num_drives7 = allowedDeadDrives(loadedDrives, years_since) if x == "dev08": h = h + 1 inst_date = date(2019, 3, 25) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 168 name8 = x num_drives8 = allowedDeadDrives(loadedDrives, years_since) if x == "dev09": i = i + 1 inst_date = date(2017, 6, 12) diff_date = ((curr_date - inst_date).days) years_since = round((diff_date / 365)) loadedDrives = 108 name9 = x num_drives9 = allowedDeadDrives(loadedDrives, years_since) # This is going to create arrays for the x-axis and y-axis disks = [a, b, c, d, e, f, g, h, i] names = [name1, name2, name3, name4, name5, name6, name7, name8, name9] ok_disks = [ num_drives1, num_drives2, num_drives3, num_drives4, num_drives5, num_drives6, num_drives7, num_drives8, num_drives9 ] # To create one array from two. It will use the previous for statement to determine how long the array is array = np.concatenate((disks, names)).reshape(2, 9) # This is for plotting fig = plt.figure(figsize=(15, 9)) plt.subplot(131) plt.scatter(library_name, disk_number, c='g', s=sizevalues1) plt.xlim(-1, 9) plt.xticks(rotation='vertical') plt.tight_layout() plt.subplot(132) real_drives = plt.scatter(names, disks, c='g', marker="o", s=100) max_drives = plt.scatter(names, ok_disks, c='r', marker="x", s=100) plt.legend([real_drives, max_drives], ["Actual drive failure", "Max theoretical failures"], loc="upper right") plt.xlim(-1, 9) plt.xticks(rotation='vertical') plt.ylim(0, 25) plt.yticks(np.arange(0, 26, 1)) plt.tight_layout(pad=3.0) canvas = FigureCanvasTkAgg(fig, master=graphing) canvas.draw() mplcursors.cursor(hover=True) toolbar = NavigationToolbar2Tk(canvas, graphing) toolbar.update() canvas.get_tk_widget().pack() graphing.mainloop()
def test_degenerate_inputs(ax): empty_container = ax.bar([], []) assert not mplcursors.cursor().artists assert not mplcursors.cursor(empty_container).artists pytest.raises(TypeError, mplcursors.cursor, [1])
ax[1, 1].plot(frequency_array2, voltage_array2, 'b', label="Respuesta en frecuencia condensador de poliester") ax[1, 1].set_xlabel("Frecuencia") ax[1, 1].set_ylabel("Magnitud [dB]") ax[1, 1].grid(True) ax[1, 1].legend(loc='upper right') ax[0, 1].plot(frequency_array3, voltage_array3, label="Respuesta en frecuencia condensador de electrolitico") ax[0, 1].set_xlabel("Frecuencia") ax[0, 1].set_ylabel("Magnitud [dB]") mplcursors.cursor() ax[0, 1].grid(True) ax[0, 1].legend(loc='upper right') mplcursors.cursor(multiple=True).connect( "add", lambda sel: sel.annotation.draggable(False)) plt.grid(True) plt.show() elif (option == "2"): archivo0 = open("./datos/vb0 poliester.csv", "r") archivo1 = open("./datos/vb0 tantalio.csv", "r") archivo2 = open("./datos/vbc.csv", "r") archivo3 = open("./datos/vbc1.csv", "r") frequency0 = [] frequency1 = [] frequency2 = []
def test_remove_while_adding(ax): ax.plot([0, 1]) cursor = mplcursors.cursor() cursor.connect("add", cursor.remove_selection) _process_event("__mouse_click__", ax, (.5, .5), 1)
"""Display a bar's height and name on top of it upon hovering. An example of using event handlers to change the annotation text and position. """ import string import matplotlib.pyplot as plt import mplcursors fig, ax = plt.subplots() ax.bar(range(9), range(1, 10), align='center') labels = string.ascii_uppercase[:9] ax.set(xticks=range(9), xticklabels=labels, title='Hover over a bar') cursor = mplcursors.cursor(hover=True) @cursor.connect("add") def on_add(sel): x, y, width, height = sel.artist.get_bbox().bounds sel.annotation.set( text="{}: {}".format(x + width / 2, height), ha="center", va="bottom") sel.annotation.xy = (x + width / 2, y + height) sel.annotation.xyann = (0, 20) plt.show()
""" Extracting data and labels from a :class:`~pandas.DataFrame` ============================================================ :class:`~pandas.DataFrame`\\s can be used similarly to any other kind of input. Here, we generate a scatter plot using two columns and label the points using a third column. """ from matplotlib import pyplot as plt import mplcursors from pandas import DataFrame df = DataFrame([("Alice", 163, 54), ("Bob", 174, 67), ("Charlie", 177, 73), ("Diane", 168, 57)], columns=["name", "height", "weight"]) df.plot.scatter("height", "weight") mplcursors.cursor().connect( "add", lambda sel: sel.annotation.set_text(df["name"][sel.target.index])) plt.show() # test: skip
"""Changing properties of the popup. """ import matplotlib.pyplot as plt import numpy as np import mplcursors fig, axes = plt.subplots(ncols=2) left_artist = axes[0].plot(range(11)) axes[0].set(title='No box, different position', aspect=1.0) right_artist = axes[1].imshow(np.arange(100).reshape(10,10)) axes[1].set(title='Fancy white background') # Make the text pop up "underneath" the line and remove the box... c1 = mplcursors.cursor(left_artist) @c1.connect("add") def _(sel): sel.annotation.xyann = (15, -15) sel.annotation.set_bbox(None) # Make the box have a white background with a fancier connecting arrow c2 = mplcursors.cursor(right_artist) @c2.connect("add") def _(sel): sel.annotation.get_bbox_patch().set(fc="white") sel.annotation.arrow_patch.set(arrowstyle="simple", fc="white", alpha=.5) plt.show()
def scatterPlot(self): #for getting list of channels csvfile = open('Channel_Names.csv', 'r',encoding="utf8",errors='ignore') fieldnames=('Channel Name','Subscribers') reader= csv.DictReader(csvfile,fieldnames) next(reader) for i in reader: name_list.append(i['Channel Name']) #for getting list of channel name and views for plotting them on x and y axis data = pd.read_csv('combined.csv') likes2= data['Likes'] views2= data['View'] channel_name2= data['Channel_Name'] tags0= data['HashTags'] #converting class pandas.core.series into list for plot likes=list(likes2) views=list(views2) channel_name= list(channel_name2) labels=list(tags0) #below code removes any filler channel names in the channel_name list filler_list=[] for j in range(len(channel_name)): for i,name in enumerate(channel_name): if name not in name_list: channel_name.remove(name) filler_list.append(i) #storing the index number of filler channel names else: continue #Views belonging to filler channel names filler_views=iter(filler_list) for i in range(len(filler_list)): views.pop(next(filler_views)) # Likes belonging to filler channel names filler_likes=iter(filler_list) for i in range(len(filler_list)): likes.pop(next(filler_likes)) #Scatter Plot plt.style.use('seaborn') t = plt.scatter(channel_name ,views,c=likes,cmap='summer',edgecolors='black',linewidths=1,alpha=0.75) plt.title('Youtube Videos') plt.xlabel('Channel Names') plt.xticks(channel_name, [str(i) for i in channel_name], rotation=90) # plt.tick_params(axis='x', which='major') plt.ylabel('Views') cbar= plt.colorbar() cbar.set_label('Likes Gradient') plt.tight_layout() #for padding the labels c2 = mplcursors.cursor(t,hover=True) @c2.connect("add") def _(sel): sel.annotation.get_bbox_patch().set(fc="red") sel.annotation.arrow_patch.set(arrowstyle='wedge', fc="white", alpha=0.3) #arrowstyle - simple,wedge,fancy # sel.annotation.set_text(data['HashTags'][sel.target.index]) sel.annotation.set_text(data['HashInfo'][sel.target.index]) plt.show()
"""Display an artist's label instead of x, y coordinates. An example of using event handlers to change the annotation text. """ import numpy as np import matplotlib.pyplot as plt import mplcursors x = np.linspace(0, 10, 100) fig, ax = plt.subplots() ax.set_title('Click on a line to display its label') # Plot a series of lines with increasing slopes. for i in range(1, 20): ax.plot(x, i * x, label='$y = {}x$'.format(i)) # Use a Cursor to interactively display the label for a selected line. mplcursors.cursor().connect( "add", lambda sel: sel.annotation.set_text(sel.artist.get_label())) plt.show()
def ej1(ventas): print('Comenzamos a divertirnos!') ''' Para comenzar a calentar en el uso del dataset se lo solicita que grafique la evolución de la facturación de la categoría alimentos para el primer mes (mes 1) de facturación. Realice un line plot con los datos de facturación de alimentos del mes 1 Deberá poder observar la evolución de ventas(y) vs días(x) TIP: 1) Para aquellos que utilicen listas siempre primero deberan emprezar filtrando el dataset en una lista de diccionarios que posee solo las filas y columnas que a están buscando. En este caso todas las filas cuyo mes = 1 y solo la columan de día(x) y de alimentos(y). Una vez que tiene esa lista de dccionarios reducida a la información de interés, debe volver a utilizar comprensión de listas para separar los datos de los días(x) y de los alimentos(y) 2) Para aquellos que utilicen Numpy, si transformaron su CSV en Numpy les debería haber quedado una matriz de 6 columnas y de 90 filas (recordar sacar la primera fila que es el header) mes | dia | alimentos | bazar | limpieza | electrodomesticos Luego si quisieramos acceder a solo la columna de los dias (col=1) podemos utilizar slicing de Numpy: dias = dataset[:, 1] ¿Cómo puedo obtener las filas solo del primer mes? Aplicando mask de Numpy: mes_1 --> col = 0 filas_mes_1 = dataset[:, 0] == 1 Obtengo solos los datos del mes uno mes_1 = dataset[filas_mes_1, :] x --> dias Obtengo solo los dias del mes1 de alimentos x = dataset[filas_mes_1, 1] o tambien puede usar x = mes_1[:, 1] y --> alimentos Obtengo solo los alimentos del mes1 de alimentos y = dataset[filas_mes_1, 2] o tambien puede usar y = mes_1[:, 2] ''' # Extraer datos de archivo ventas.csv ventas = [{ 'Dia': int(ventas[x].get('Dia')), 'Alimentos': int(ventas[x].get('Alimentos')) } for x in range(len(ventas)) if ventas[x].get('Mes') == '1'] # formar listas para graficar dia = [x['Dia'] for x in ventas] venta_alimentos = [x['Alimentos'] for x in ventas] # gráfico line plot fig = plt.figure('ventas.csv') ax = fig.add_subplot() ax.plot(dia, venta_alimentos, color='r', marker='.', label='Cantidad vendida') ax.set_facecolor('whitesmoke') ax.set_title('Mes Enero: VENTA DE ALIMENTOS') ax.set_ylabel('Cantidad') ax.set_xlabel('Dia') ax.legend() ax.grid(ls='solid') mplcursors.cursor(multiple=True) plt.show()