Charmonium production in pp collisions at center-of-mass energy of √s = 13 TeV and p-Pb collisions at center-of-mass energy per nucleon pair of √sNN = 8.16 TeV is studied as a function of charged-particle pseudorapidity density with ALICE. Ground and excited charmonium states (J/ψ, ψ(2S)) are measured from their dimuon decays in the interval of rapidity in the center-of-mass frame 2.5<ycms<4.0 for pp collisions, and 2.03<ycms<3.53 and −4.46<ycms<−2.96 for p-Pb collisions. The charged-particle pseudorapidity density is measured around midrapidity (|η|<1.0). In pp collisions, the measured charged-particle multiplicity extends to about six times the average value, while in p-Pb collisions at forward (backward) rapidity a multiplicity corresponding to about three (four) times the average is reached. The ψ(2S) yield increases with the charged-particle pseudorapidity density. The ratio of ψ(2S) over J/ψ yield does not show a significant multiplicity dependence in either colliding system, suggesting a similar behavior of J/ψ and ψ(2S) yields with respect to charged-particle pseudorapidity density. The results are also compared with model calculations.